What is the explanation for &:hex in ruby? [duplic

2019-08-31 07:45发布

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

2条回答
三岁会撩人
2楼-- · 2019-08-31 08:06

These two expressions are equivalent:

foo.map {|x| x.hex}
foo.map &:hex
查看更多
Evening l夕情丶
3楼-- · 2019-08-31 08:18

In this case & takes an object and if the object is not already a Proc, as it is the case with the Symbol :hex it will try to invoke the method to_proc on it. In the Symbol documentation you will find the implementation detail for the to_proc method:

to_proc

Returns a Proc object which respond to the given method by sym.

(1..3).collect(&:to_s)  #=> ["1", "2", "3"]

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 are Proc and Lambda.

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 like map 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 to Proc.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.

查看更多
登录 后发表回答