Skip to content

Instantly share code, notes, and snippets.

@cp
Created June 19, 2014 02:12
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 cp/056c237c5fe3112524e8 to your computer and use it in GitHub Desktop.
Save cp/056c237c5fe3112524e8 to your computer and use it in GitHub Desktop.
# These two approaches are not the same:
class Person2
def self.first_name
full_name.split(' ').first
end
private
def self.full_name
'Ben Franklin'
end
end
puts Person2.first_name # => Ben
puts Person2.full_name # => Ben Franklin (no exception raised)
class Person1
class << self
def first_name
full_name.split(' ').first
end
private
def full_name
'Ben Franklin'
end
end
end
puts Person1.first_name # => Ben
puts Person1.full_name # Raises exception
# Recommended reading:
#
# http://yehudakatz.com/2009/11/15/metaprogramming-in-ruby-its-all-about-the-self/
# http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html
# http://www.amazon.com/Metaprogramming-Ruby-Program-Like-Pros/dp/1934356476
#
# There is one hack to get around this if you INSIST on using the `self.` approach:
class Person3
def self.first_name
full_name.split(' ').first
end
def self.full_name
'Ben Franklin'
end
private_class_method :full_name # See http://ruby-doc.org/core-1.9.3/Module.html#method-i-private_class_method
end
puts Person3.first_name # => Ben
puts Person3.full_name # Raises exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment