Skip to content

Instantly share code, notes, and snippets.

@willmurphyscode
Created March 6, 2017 11:57
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 willmurphyscode/ee963d6b55c7a838d620423064d3ee20 to your computer and use it in GitHub Desktop.
Save willmurphyscode/ee963d6b55c7a838d620423064d3ee20 to your computer and use it in GitHub Desktop.
Error calling class methods from instance methods in Ruby
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