Created
March 6, 2017 11:57
-
-
Save willmurphyscode/ee963d6b55c7a838d620423064d3ee20 to your computer and use it in GitHub Desktop.
Error calling class methods from instance methods in Ruby
This file contains 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 HasInstanceMethods | |
def instance_method | |
puts "In instance method, the type of `self` is #{self.class}" | |
end | |
def self.class_method | |
puts "In class method, the type of `self` is #{self.class}" | |
end | |
def call_class_from_instance | |
begin | |
class_method # raise NameError | |
rescue Exception => e | |
puts "raised #{e.inspect}" | |
end | |
end | |
def call_self_class_from_instance | |
self.class.class_method # works | |
end | |
end | |
instance = HasInstanceMethods.new | |
instance.instance_method # works | |
HasInstanceMethods.class_method # works | |
# would raise NoMethodError: | |
# instance.class_method | |
instance.call_class_from_instance # NameError | |
instance.call_self_class_from_instance # works | |
# ouptut: | |
# In instance method, the type of `self` is HasInstanceMethods | |
# In class method, the type of `self` is Class | |
# raised #<NameError: undefined local variable or method `class_method' for #<HasInstanceMethods:0x007fc88709d380>> | |
# In class method, the type of `self` is Class | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment