Why does Ruby allow symbolic methods to be referenced when calling to_proc on them?

It works:

strings = ["1", "2", "3"]
nums = strings.map(&:to_i)

We see that the ( to_proc ) method applied to the Symbol object turns into a block. This, however, does not work:

strings = ["1", "2", "3"]
nums = strings.map(&to_i)
nums = strings.map("to_i".to_sym.to_proc) #...neither does this

Why is this not working? Is there an alternative way to write the code above? I got confused because there are two ways to access the class method:

"1".method(:to_i).call #works as well as
"1".method("to_i").call 

Thus, the method name can be obtained either by character or by string.

+4
source share
2 answers

Given the following Ruby example:

"to_i".to_sym.to_proc.call("1")

To call #to_procon Symbol, a proc is created that takes one parameter: the object that should receive the call to the method called the symbol. Something like that:

->(object) {
  object.send(:to_i)
}

&, , #to_proc . Enumerable#map , .

, ["1", "2"].map(&:to_i) - - :

block = ->(el) {
  el.send(:to_i)
}

["1", "2"].map &block

:

&to_i Ruby to_i. scope ( String Array, "" ), .

: "to_i".to_sym.to_proc :to_i proc, , (:to_i), . , & proc "-":

["1", "2"].map(&"to_i".to_sym.to_proc)
+4
nums = strings.map(&to_i)

, to_i .

nums = strings.map("to_i".to_sym.to_proc)

, Proc . .

:

nums = strings.map(&"to_i".to_sym)
0

Source: https://habr.com/ru/post/1624851/


All Articles