In a class definition, what is the difference between these two methods?
def func(var)
...
end
def func=(var)
...
end
Is there any, or is one of them not valid?
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.
To explain some things about reader/writer AKA getter/setter methods in Ruby:
Ruby doesn’t force us to use
=in the method definition for a setter. We get to choose whether the method has one.Consider this:
Running the code outputs:
The
=is simply another letter in the method name because Ruby is smart enough to know if it seesf.setter = 3it should use thesetter=(v)method.Ruby doesn’t force using
=to set a variable, you can decide if it makes more sense to you when you define the method. It is idiomatic that we use=because it helps make a setter look like an assignment, removing the urge to name all the setters something likeset_v(v).