Created
June 19, 2014 02:12
-
-
Save cp/056c237c5fe3112524e8 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
# 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