Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Ruby 1.9.2 vs 1.9.3, gotcha with Struct.new and constant scope
# Define a simple class with a DEBUG constant
#
Connection = Struct.new(:name, :state) do
DEBUG = false
def self.debug?
DEBUG
end
end
# A quick sanity check
Connection.debug?
=> false
# Let's now change the constant from false to true
Connection::DEBUG = true
# ruby 1.9.2-p180
Connection.debug?
=> true
# ruby 1.9.3-p0
Connection.debug?
=> false
DEBUG = false
Connection = Struct.new(:name, :state) do
def self.debug?
DEBUG
end
end
# ruby 1.9.2-p180
Connection::DEBUG = true # Actually does DEBUG=true
Connection.debug? # Reads new value of DEBUG
=> true
# ruby 1.9.3-p0
Connection::DEBUG = true # Creates new constant Connection::DEBUG
Connection.debug? # Reads unchanged value of DEBUG
=> false
Connection = Struct.new(:name, :state) do
def self.debug?
Connection::DEBUG
end
end
Connection::DEBUG = false
class Connection
DEBUG = false
attr_accessor :name
attr_accessor :state
def init(name, state)
@name = name
@state = state
end
def self.debug?
DEBUG
end
end
Owner

mattbrictson commented Jan 25, 2012

Read the blog post for a detailed explanation of this Gist: http://blog.55minutes.com/post/16472600410/trivia-constants-in-ruby-1-9-2-vs-1-9-3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment