Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `send` fail with Ruby 2.0 refinement?

Tags:

ruby

ruby-2.0

Why does this not work?

module StringRefinement
  refine String do
    def bar
      length
    end
  end
end

using StringRefinement
"abcdefghijklmnopqrstuvwxyz".send(:bar)
#NoMethodError: undefined method 'bar' for "abcdefghijklmnopqrstuvwxyz":String

Can someone explain why send doesn't work here? And is there a way to dynamically call methods defined in a refinement? I can't seem to find a good, full explanation of how refinements work in Ruby 2.0.

like image 534
Sean Mackesey Avatar asked Mar 07 '13 04:03

Sean Mackesey


1 Answers

Because the specification says so:

Indirect method accesses

Any indirect method access such as Kernel#send, Kernel#method, and Kernel#respond_to? shall not honor refinements in the caller context during method lookup.

like image 160
Jörg W Mittag Avatar answered Sep 23 '22 05:09

Jörg W Mittag