Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Can someone point me to a good primer just explaining the different syntactic features in Ruby/Rails? For instance, how come some examples I see do myMethod(x: "z") and others do myMethod(:x => "x")?
The syntax in general seems strange to me, just looking for a quick at-a-glance reference to use as a cheat sheet.
They are the same, it is just a matter of preferences.
I also asked myself why would we add this new syntax if we already have one? Well, Programming with Ruby implies that we are lazy and want to type the less possible caracters. So this new syntax allow us - lazy programmers - to write the same thing, minus 1 caracter!
But keep in mind some stuff, like the type of the keys for instance (Ruby 1.9.3):
> {a: 12}.class
=> Hash
> {:a => 12}.class
=> Hash
> {'a' => 12}.keys.first.class
=> String
> {a: 12}.keys.first.class
=> Symbol
Also, some declaration are illegal with the new syntax:
> { '1-2' => "something" }
=> {"1-2"=>"something"}
> { 1-2: "something" }
SyntaxError: (irb):38: syntax error, unexpected ':', expecting tASSOC
{ 1-2: "something" }
^
(irb):38: syntax error, unexpected '}', expecting $end
For more informations: Is there any difference between the `:key => "value"` and `key: "value"` hash notations?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
What can be the reason of string capitalization not working?
A database column:
t.string "name", limit: 255
Some example:
flower_name = Flower.find_by(id: 1).name #=> "chamomile©"
Trying to capitalize (got the same output):
flower_name.capitalize #=> "chamomile©"
Checking if it is string:
flower_name.is_a?(String) #=> true
capitalize works with ASCII characters only. Is there any chance your string contains non-ascii letters?
Try
flower_name.mb_chars.capitalize.to_s
mb_chars method may help you if you are using Rails >= 3.
'æ-ý'.mb_chars.upcase
=> "Æ-Ý"
If you're not using Rails, you can:
use directly active_support gem:
require 'active_support/core_ext/string/multibyte'
try unicode gem.
I hope you will find an answer in this similar question: Special character uppercase
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code is
for i in 0..array_dif.count-1
a = array_dif[i] - array_dif[0]
b = array_dif[array_dif.count-1] - array_dif[0]
norm = a.0/b
array_norm[i] = norm
end
And i'm getting the following error:
rb:135: no .<digit> floating literal anymore; put 0 before dot (SyntaxError)
norm = a.0/b
^
C:/piegas/config/initializers/backtrace_silencers.rb:135: syntax error, unexpected tINTEGER, expecting '('
norm = a.0/b
^
I don't know whats wrong with it
norm = a.0/b is an invalid statement (aka SyntaxError).
What do you want that statement to do?
norm = a/b might make sense.
norm = array_dif[0]/b might also make sense.
But without knowing the purpose of the code, it's difficult to know what the correct solution is.
What do you mean by a.0/b? It is invalid. If you were trying to convert a to float then it would be a.to_f/b.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there a way to create a regex for initials without using back references? For example, say I want initials for
New.York
And the regex to output
N.Y. (or n.y)
So far I have the following:
.\.[a-zA-Z]+
This outputs the last the initial of the first word instead of the first initial: w.y.
UPDATE**
I'm also assigned the RegExp to variable and using the =~ to test some things.
You could remove all the lowercase letters using gsub function,
irb(main):004:0> str = "New.York"
=> "New.York"
irb(main):006:0> str.gsub(/[a-z]+/, "")
=> "N.Y"
A ruby way to do this given your input of "New.York" could be:
str.split('.').collect { |s| s[0] }.join('.')
which would return 'N.Y'
Use this regex and you should only output the groups \1 and \2.
([a-zA-Z])[^.]*\.([a-zA-Z]).*?\b
DEMO
If you want to do a replacement you should use \1.\2
You could use the capital letters to dictate the regex match using something like this:
[15] pry(main)> str
=> "New.York"
[16] pry(main)> str.scan(/[A-Z]+/).join('.')
=> "N.Y"
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am using Ruby on Rails to make a university-exclusive website that categorizes all registered users into their specific universities via their ".edu" email. Nearly all US-based universities have an "xyz.edu" email domain. In essence, everyone that signs up with their ".edu" email would all be categorized with a similar "domain.edu".
I've searched for a regex to look for like-domains.edu and assign them into a variable or specific indexes, but I must be looking in the wrong place because I cannot find how to do this.
Would I use regex for this? Or maybe a method after their email has been verified?
I would appreciate any help or feedback I can get.
You could use a regex to extract domain names:
"gates#harvard.edu" =~ /.*#(.*)$/
This simple regexp will capture everything after the # symbol. You can experiment more with this regexp here.
However, what you have to think about is how to handle cases like gates#harvard.edu vs gates#seas.harvard.edu.
My example will parse them out as different entities: harvard.edu vs seas.harvard.edu.
I would probably go ahead and create an institution/university/group model that would hold those users. It would be easier now than later down the line. But, in an effort to answer your question, you could do something like:
array_of_emails = ['d#xyz.edu', 'a#abc.edu', 'c#xyz.edu', 'b#abc.edu' ]
array_of_emails.sort_by! { |email| "#{email[email.index('#')..-1]}#{email[0..email.index('#')]}" }
EDIT: Changed sort! to sort_by!
Dealing with domains is going to get a lot more complex in the future, with new TLDs coming on line. Assuming that .edu is the only educational TLD will be wrong.
A simple way to grab just the domain for now is:
"gates#harvard.edu"[/(#.+)$/, 1] # => "#harvard.edu"
That will handle things like:
"gates#mail.harvard.edu"[/(#.+)$/, 1] # => "#mail.harvard.edu"
If you don't want the #, simply shift the opening parenthesis right one character:
pattern = /#(.+)$/
"gates#harvard.edu"[pattern, 1] # => "harvard.edu"
"gates#mail.harvard.edu"[pattern, 1] # => "mail.harvard.edu"
If you want to normalize the domain to strip off sub-domains, you can do something like:
pattern = /(\w+\.\w+)$/
"harvard.edu"[pattern, 1] # => "harvard.edu"
"mail.harvard.edu"[pattern, 1] # => "harvard.edu"
which only grabs the last two "words" that are separated by a single ..
That's somewhat naive, as non-US domains can have a country code, so if you need to handle those you can do something like:
pattern = /(\w+\.edu(?:\.\w+)?)$/
"harvard.edu"[pattern, 1] # => "harvard.edu"
"harvard.edu.cc"[pattern, 1] # => "harvard.edu.cc"
"mail.harvard.edu.cc"[pattern, 1] # => "harvard.edu.cc"
And, as to whether you should do this before or after you've verified their address? Do it AFTER. Why waste your CPU time and disk space processing invalid addresses?
array_of_emails = ['d#xyz.edu', 'a#abc.edu', 'c#xyz.edu', 'b#abc.edu' ]
x = array_of_emails.sort_by do | a | a.match(/#.*/)[0] end
x.each do |a|
puts a
end
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am not sure if I can ask about programming conventions on stackoverflow, but since my goal is to be better at programming coding and stylistically, I guess it cannot hurt.
I would like to know what is the best style to write a hash in ruby
I have seen
a = {a: 'a', b: 'b'}
b = { a: 'a', b: 'b' }
c = {:a=>'a', :b=>'b'}
d = {:a => 'a', :b => 'b'}
e = { :a => 'a', :b => 'b' }
I prefer the first because it matches arrays [a, b, c] or param('a', 'b')
but I have seen tutorials using the second style.
I know there might be personal preference but I want to know the convention like 'tabs should be two spaces instead of four'.
I know the hash rocket is older syntax, lets assume I'm using the newest rails and ruby verions.
From the Ruby Style Guide
# good - space after { and before }
{ one: 1, two: 2 }
# good - no space after { and before }
{one: 1, two: 2}
I personally favor
a = {a: 'a', b: 'b'}
The => are part of the old <= 1.8 hash syntax
Note, when using hashes in method calls, you can omit the {}
some_method a: 'a', b: 'b'
This is totally an opinion question, but my opinion answer is "B" above... It's easiest to read and is the newest "standard" for hashes. That said, there's nothing wrong with "A", but I think the extra spaces makes it easier to read.
Full disclosure, I still prefer "E" - I've never gotten away from hashrockets... But I'm old school like that.