This question already has an answer here:
I am trying to figure out what &:hex mean in this code
sort_by{|x|x.scan(/\d*/).map &:hex}
The full code looks like this
class Array
def version_sort
sort_by{|x|x.scan(/\d*/).map &:hex}
end
end
I know that map does an action to the scanned part , so I am guessing it replaces numbers
(/\d*/)
with
&:hex
but I dont know what that means
These two expressions are equivalent:
In this case
&
takes an object and if the object is not already aProc
, as it is the case with the Symbol:hex
it will try to invoke the methodto_proc
on it. In the Symbol documentation you will find the implementation detail for theto_proc
method:In your case through
&:hex
the symbol:hex
will be converted into the Proc object which is equivalent to{ |item| item.hex() }
What is a Proc exactly? Basically the Proc class is a basic anonymous function. In Ruby the notion of a callable object is embodied in Ruby through objects to which you can send the message
call
. The main representatives of these kind areProc
andLambda
.Proc objects are self-contained code sequences, that can be created, stored, passed around as method arguments and executed at some point through
call
. A method likemap
can also take a block as an argument which is the case if you pass&:hex
.In the method definition of
map
a kind of implicit call toProc.new
is made using the very same block. Then the Proc is executed through its call method executing the code embodied by the Proc object.