What does class << self do in Ruby?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, the
class << foosyntax opens upfoo‘s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.Now, to answer the question:
class << selfopens upself‘s singleton class, so that methods can be redefined for the currentselfobject (which inside a class or module body is the class or module itself). Usually, this is used to define class/module (“static”) methods:This can also be written as a shorthand:
Or even shorter:
When inside a function definition,
selfrefers to the object the function is being called with. In this case,class << selfopens the singleton class for that object; one use of that is to implement a poor man’s state machine:So, in the example above, each instance of
StateMachineExamplehasprocess_hookaliased toprocess_state_1, but note how in the latter, it can redefineprocess_hook(forselfonly, not affecting otherStateMachineExampleinstances) toprocess_state_2. So, each time a caller calls theprocessmethod (which calls the redefinableprocess_hook), the behaviour changes depending on what state it’s in.