This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 8 years ago.
I saw it in some sample Ruby code someone had posted. It was something like:
a.sort_by(&:name)
where a is an array or ActiveRecord objects and :name is one of the attributes.
I have never seen &:name and Ruby's Symbol class documentation says nothing about it. Probably something really simple. :)
Unary Ampersand is address of a function/block/lambda
In this case, it means that the .sort_by function will use each a's element's function named name for comparison
Mostly it used for something else, like this:
[1,2,3].map{ |x| x.to_s } # ['1','2','3']
That could be shortened as:
[1,2,3].map(&:to_s)
So, in your case, a.sort_by(&:name) is a shorthand to:
a.sort_by{ |x| x.name }
Related
This question already has answers here:
What are <-- Ruby Strings called? And how do I insert variables in them?
(3 answers)
Closed 6 years ago.
I'm working on Rails. In my code base, I see a line that using Arel::SqlLiteral like this:
result = Arel::Nodes::SqlLiteral.new(<<-SQL
CASE WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
ELSE default_calculation END
SQL)
I understand what this code piece do. The thing I don't understand is its grammar, at this point:
Arel::Nodes::SqlLiteral.new(<<-SQL
...
SQL
)
So in ruby, what is the grammar of <<- follow by name, and then at last block we call that name.
thanks
The keyword you're looking for is "Heredoc".
https://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents
It's mainly used to prettify large texts and common practice for shells/shellscripts. The marker on top indicates the beginning of a heredoc and the marker on bottom (which must not be indented unless you place a “-” before the opening marker) specifies the end.
This question already has answers here:
what is "?" in ruby
(3 answers)
Closed 7 years ago.
I am trying to understand what this means
variableName * ?*
I understand that VariableName is being multiplied with something, but what does ?* mean? Is this regex and does it mean that I'm appending '?' and anything that comes after it?
?c is not a regex, is the short syntax for '*'. That is, ?a is 'a', ?b is 'b' etc...
What is going on in your program is probably something like:
["ab","cd","ef"] * ?*
#=> "ab*cd*ef"
This question already has answers here:
How do I convert a String object into a Hash object?
(16 answers)
Closed 8 years ago.
I have a string. {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", :cents=>100} that is stored as a value in hstore in postgresql.
So it's a raw string not a YAML or a JSON.
I was wonering how to get the value back to the hash that was used to insert the record.
The idea of using EVAL scares the hell out of me, because there is potential for use input here.
This question might seem to be a replica of How to convert a string to a hash in ruby/rails without using eval?, but the answer there doesn't mesh with the question. It only offers eval as the solution. (I don't understand how the answer was marked as the answer)
Ruby hashes look pretty similar to JSON, so this would work for your example:
require 'json'
str = "{\"response_code\"=>\"SUCCESS\", \"authorisation_result\"=>\"Approved\", \"transaction_number\"=>\"1234567\", \"receipt_number\"=>\"999999\", :cents=>100}"
JSON.parse str.gsub(/:(\w+)/){"\"#{$1}\""}.gsub('=>', ':')
# => {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", "cents"=>100}
This question already has answers here:
Is there any difference between the `:key => "value"` and `key: "value"` hash notations?
(5 answers)
Closed 7 years ago.
I am struggling to understand difference between :symbol and text: with regards to the colon placement. My understanding is that when we use :symbol we are referring to this object and whatever it contains, where as text: is used to assign a value to the text like we would a variable. Is this correct or could someone elaborate on the usage. Thank you.
:whatever is a symbol, you've got that part right.
When you're using a hash, this was how you used to define it in 1.8x ruby:
{:key => value, :another_key => another_value}
This is known as the hashrocket syntax. In ruby 1.9x, this changed to:
{key: value, another_key: another_value}
There is backward compatibility that will still load the hashrocket syntax... But, in 1.9, 'key:' is a symbol
the {:key => value} is the old hash syntax in ruby, now we have a new hash syntax that is more like json so
{:key => value}
is the same as
{key: value}
The old one, we’re all familiar with is:
old_hash = {:simon => "Talek", :lorem => "Ipsum"}
This is all nice and dandy, but it could be simpler and cleaner. Check out the Ruby 1.9 style, it sort of resembles JSON:
new_hash = {simon: "Talek", lorem: "Ipsum"}
But now you look closer and ask, “But previously the key was a symbol explicitly, what’s with this now?”.
Well you’re right, the new notation is sort of a syntactic sugar for the most common style of hashes out there, the so called symbol to object hash. If you do this in the irb, you’ll see ruby returning the old school hash, with the symbols used as keys:
> new_hash = {simon: "Talek", lorem: "Ipsum"}
=> {:simon=>"Talek", :lorem=>"Ipsum"}
If you need to have arbitrary objects as your hash keys, you’ll still have to do it old school.
ref:http://breakthebit.org/post/8453341914/ruby-1-9-and-the-new-hash-syntax
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does map(&:name) mean in Ruby?
What does the &:valid? found in the each mean?
I've seen .each do |r| or whatever, but not sure how this one works?
The & is called the to_proc operator. It expands the symbol (:valid?) into a Proc.
So your example is equivalent to:
temps.each { |t| t.valid? }
&:symbol is a shorthand for symbol to proc.
Here's a good blog post on it.
http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand