Why would I want to add anything to a class using class << Class
syntax?
class Fun
def much_fun
# some code here
end
end
class << Fun # the difference is here!
def much_more_fun
# some code here
end
end
instead of using the monkey patching/duck punching method:
class Fun
def much_fun
# some code here
end
end
class Fun # the difference is here!
def much_more_fun
# some code here
end
end
While reading Why's Poignant Guide to Ruby I came across:
Why defines a class LotteryDraw
:
class LotteryDraw
# some code here
def LotteryDraw.buy( customer, *tickets )
# some code here as well
end
end
and after a while adds a method to the LotteryDraw
class:
class << LotteryDraw
def play
# some code here
end
end
saying that:
When you see
class << obj
, believe in your heart, I’m adding directly to the definition ofobj
.
What is the purpose of this syntax? Why did Why decide to do it this way instead of using the monkey patching method?
These are some related questions and websites:
- Adding a new method to the Array class
- Yield in class << self in class method, which gives me a little bit of an idea why I would like to use
class << Class
syntax. - Open Classes in Ruby