Skip to content

Instantly share code, notes, and snippets.

@mattbrictson
Created January 24, 2012 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbrictson/1673289 to your computer and use it in GitHub Desktop.
Save mattbrictson/1673289 to your computer and use it in GitHub Desktop.
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
@mattbrictson
Copy link
Author

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