Unable to qualify string with CONSTANT

I'm currently studying refinements in Ruby 2.1.1, and I am running into something weird. I am trying to clarify the String class and define a constant named 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 an uninitialized constant String::FOO (NameError) . However, I can call "".foobar , which makes me believe that I am in the right volume.

Which is strange, 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 not a clarifying version of this work, as I expect?

+7
ruby
source share
2 answers

You cannot refine constants and class variables with Refinements.

Source: Matz Comment

+1
source share

Disclaimer - This answer is not intended. Just some research.

About refine :

The idea of refine is to provide temporary, limited access to the class. The function is experimental ( Refinements are experimental, and the behavior may change in future versions of Ruby! ), Sometimes the behavior is strange (as in your case).

About the area:

You are a String constant of class FOO in another scope:

 => module Baz => class String => FOO = "ADw" => end => puts "".class::FOO # <- this should work ? => end => "".class::FOO #> NameError: uninitialized constant String::FOO => Baz::String.new.class::FOO #> "ADw" => String::FOO #> uninitialized constant String::FOO => Baz.constants #> [:String] 

Some update:

 => module Bar => refine String do #> WOO = "Fo" => end => end => #<refinement: String@Bar > => Bar.constants => [:WOO] 
0
source share

All Articles