Last active
November 17, 2020 21:19
-
-
Save softcraft-development/59b279ea9bc10b84d4a9f7d631fb54a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
CONST_ON_FOO = "the constant on Foo" | |
class << self | |
puts "When we're defining CONST_ON_FOOS_CLASS, we're actually in: #{self}, a #{self.class}" | |
CONST_ON_FOOS_CLASS = "the constant on Foo's class" | |
end | |
end | |
instance = Foo.new | |
puts "Foo's class: #{Foo}" | |
puts "The instance of Foo: #{instance}" | |
puts "Getting Foo's const directly from the Foo class: #{Foo::CONST_ON_FOO}" | |
begin | |
puts "Getting Foo's const via the instance (does not work): #{instance::CONST_ON_FOO}" | |
rescue StandardError => e | |
puts "Can't reference CONST_ON_FOOS_CLASS via the instance" | |
puts e | |
end | |
puts "Getting Foo's const via the instance's class: #{instance.class::CONST_ON_FOO}" | |
begin | |
puts "Getting Foo's eigenclass's const via Foo (doesn't work): #{Foo::CONST_ON_FOOS_CLASS}" | |
rescue StandardError => e | |
puts "Can't reference Foo::CONST_ON_FOOS_CLASS" | |
puts e | |
end | |
begin | |
puts "Getting Foo's eigenclass's const via Foo.class (doesn't work): #{Foo.class::CONST_ON_FOOS_CLASS}" | |
rescue StandardError => e | |
puts "Can't reference Foo.class::CONST_ON_FOOS_CLASS" | |
puts e | |
end | |
puts "Getting Foo's eigenclass's const via Foo.singleton_class class: #{Foo.singleton_class::CONST_ON_FOOS_CLASS}" | |
# Output: | |
# When we're defining CONST_ON_FOOS_CLASS, we're actually in: #<Class:Foo>, a Class | |
# Foo's class: Foo | |
# The instance of Foo: #<Foo:0x00007fcfaf0ebcb8> | |
# Getting Foo's const directly from the Foo class: the constant on Foo | |
# Can't reference CONST_ON_FOOS_CLASS via the instance | |
# #<Foo:0x00007fcfaf0ebcb8> is not a class/module | |
# Getting Foo's const via the instance's class: the constant on Foo | |
# Can't reference Foo::CONST_ON_FOOS_CLASS | |
# uninitialized constant Foo::CONST_ON_FOOS_CLASS | |
# Can't reference Foo.class::CONST_ON_FOOS_CLASS | |
# uninitialized constant Class::CONST_ON_FOOS_CLASS | |
# Getting Foo's eigenclass's const via Foo.singleton_class class: the constant on Foo's class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment