I'm currently exploring refinements in Ruby 2.1.1 and I'm running into something odd. I'm trying to refine the String class and define a constant called FOO.
sandbox.rb
module Foobar
  refine String do
    FOO = "BAR"
    def foobar
      "foobar"
    end
  end
end
using Foobar
puts "".class::FOO # => uninitialized constant String::FOO (NameError)
puts "".foobar # => "foobar"
This gives me uninitialized constant String::FOO (NameError). I can however call "".foobar which leads me to believe this I am in the correct scope. 
What's odd is that if I open  the String class and define FOO I get a different result.
sandbox.rb
class String
  FOO = "BAR"
end
puts "".class::FOO # => "BAR"
Why doesn't the refinement version of this work as I expect?
You can't refine constants and class variables with Refinements.
Source: comment by Matz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With