红宝石中的&:hex的解释是什么? [英] What is the explanation for &:hex in ruby?
问题描述
我试图找出这个代码中的&:hex的含义。
sort_by {| x | x.scan (/\d*/).map&:hex}
完整的代码如下所示
class Array
def version_sort
sort_by {| x | x.scan(/ \ d * /).map&:hex}
end
end
我知道该地图对扫描的部分执行了一个操作,所以我猜测它会替换数字
(/ \ d * /)
with
&:hex
但我不知道这意味着什么$ b $在这种情况下,&
取一个对象,如果该对象不是一个 Proc
,因为它是符号:hex
的情况下,它会尝试调用方法 to_proc
。在 Symbol 文档中,您会找到实现 to_proc
方法的详细信息:
to_proc
返回一个Pro对象,它通过sym来响应给定的方法。
(1..3).collect(&:to_s)#=> [1,2,3]
在你的情况下,通过&:hex
符号:hex
将被转换成Proc对象相当于 {| item | item.hex()}
什么是Proc?基本上,Proc类是一个基本的匿名函数。在Ruby中,可调用对象的概念通过可以发送消息 call
的对象在Ruby中体现。这些类型的主要代表是 Proc
和 Lambda
。
< Proc对象是自包含的代码序列,可以创建,存储,作为方法参数传递,并通过
call
执行。像 map
这样的方法,如果你传递&:hex
,也可以将一个块作为参数。 $ b $
在 map
的方法定义中,隐式调用 Proc.new
是使用同一个块创建的。然后Proc通过其执行由Proc对象体现的代码的调用方法执行。
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
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.
这篇关于红宝石中的&:hex的解释是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!