Reputation: 7616
i'm really confused how to name method names in Ruby classes. if i create an accessor like: attr_accessor :name
it creates to methods: name and name=
but when i call the second method with a whitespace between the 'name' and '=' it works
'n.name=' and 'n.name =' both works.
i read somewhere that Ruby ignores whitespaces. Well then, why a method written by me does not work when i call it with whitespace?
def getname end
if i call this way, it doesn't work. why? t.get name
i'm not surprised as it does not work. but i'm confused how the setter method (name=) works then?
thanks in advance.
Upvotes: 0
Views: 675
Reputation: 14941
Setters are special in Ruby.
In fact, defining a method name ending in an equals sign makes that name eligible to appear on the left-hand side of an assignment.
from http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html
Assignments are defined in Ruby as:
An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue).
from http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html
So n.name=
is calling the setter name=
directly.
n.name =
is using this special treatment of setters by the fact that it ends in an =
, to make it so that you can use it as the lvalue (that is, it can appear on the left side) in an assignment.
Upvotes: 3
Reputation: 420
getName is the name of the method, so you cannot have whitespace in that because then it thinks it is two methods or maybe a parameter, that is why we camal case to make it readable. But the equal sign is an operand and there can be space around that. Its the same as say '2+2' and '2 + 2'. Hope that helps
Upvotes: 1