Skip to content

Instantly share code, notes, and snippets.

@nevans
Created August 19, 2011 15:50
Show Gist options
  • Save nevans/1157133 to your computer and use it in GitHub Desktop.
Save nevans/1157133 to your computer and use it in GitHub Desktop.
demonstrating the difference between method and constant lookup
#!/usr/bin/env ruby
module TopLevel
CONST_D = :d_from_top_level
module MiddleLevel
class BottomLevel
CONST_A = :foo
CONST_B = :bar
CONST_C = :c_from_bottom_level
# does not behave like you would expect for method lookup
def const_c; CONST_C; end
def const_d; CONST_D; end
# just won't work
def const_undefined; CONST_DEFINED_IN_CLASS_A; end
end
end
end
class A < TopLevel::MiddleLevel::BottomLevel
CONST_B = "Abar"
CONST_C = "c from class A"
CONST_D = "d from class A"
CONST_DEFINED_IN_CLASS_A = "only defined in class A"
# behaves like you would expect method lookup:
def const_a; CONST_A; end
def const_b; CONST_B; end
def our_own_const_d; CONST_D; end
# might confuse you, if you aren't careful:
def const_d_from_a; const_d; end
# just to demonstrate the flipside of const_undefined
def const_defined_here; CONST_DEFINED_IN_CLASS_A; end
end
def safely_puts
puts yield
rescue => ex
puts "Exception! => #{ex}"
end
safely_puts { A.new.const_a }
safely_puts { A.new.const_b }
safely_puts { A.new.const_c }
safely_puts { A.new.const_d }
safely_puts { A.new.const_d_from_a }
safely_puts { A.new.our_own_const_d }
safely_puts { A.new.const_undefined }
safely_puts { A.new.const_defined_here }
foo
Abar
c_from_bottom_level
d_from_top_level
d_from_top_level
d from class A
Exception! => uninitialized constant TopLevel::MiddleLevel::BottomLevel::CONST_DEFINED_IN_CLASS_A
only defined in class A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment