Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot refine String with CONSTANT

Tags:

ruby

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?

like image 495
Kyle Decot Avatar asked Jul 31 '14 14:07

Kyle Decot


1 Answers

You can't refine constants and class variables with Refinements.

Source: comment by Matz

like image 152
Pak Avatar answered Oct 16 '22 15:10

Pak