Why doesn't to_proc work inside Ruby?

It to_procdoesn't seem to work on the methods defined in the refinements:

module ArrayExtensions
  refine Array do
    def sum
      reduce(0, :+)
    end
  end
end

using ArrayExtensions

puts [[1, 2, 3]].map { |array| array.sum } # => 6
puts [[1, 2, 3]].map(&:sum) # => array.rb:13:in `map': undefined method `sum' for [1, 2, 3]:Array (NoMethodError)
puts [1, 2, 3].method(:sum).to_proc.call # => array.rb:14:in `method': undefined method `sum' for class `Array' (NameError)

Is this intended behavior? Is there a workaround?

+4
source share
2 answers

The scope of the refinement is limited by the current context. Since refinements are not global, unlike monkey patches, any attempt to name the cleaned method from the outside is prevented. In the code below:

puts [[1, 2, 3]].map { |array| array.sum } # => 6

the scope is beautiful, we are inside the same area where this refinement was defined. But here:

puts [[1, 2, 3]].map(&:sum)

the scope is transferred to the class context Symbol(!). As stated in the documentation:

, .

. , , , , . , . :)

P.S. !

+2

, . - , using. (&:sum) () sum; :sum. - Ruby C-, Symbol#to_proc. - , .

.

+1

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


All Articles