0

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.

2 Answers 2

3

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.

1

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

2
  • but in setter, the = is the part of the method name. isn't it? Mar 26, 2012 at 5:55
  • In Ruby, variable and method names should be in lower case and words should be separated by underscores. Use of camel case is strongly discouraged, except in class names. Mar 26, 2012 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.