the12 the12 - 1 month ago 6
Ruby Question

How does Ruby distinguish between someMethod and someMethod = (parameter) (same name getter/setter methods)?

Given the following code:

class Animal
def noise=(noise)
@noise = noise
end

def noise
@noise
end
end

animal1 = Animal.new
animal1.noise = "Moo!"
puts animal1.noise

animal2 = Animal.new
animal2.noise = "Quack!"
puts animal2.noise


How does Ruby distinguish between noise and noise = (parameter)? Usually when two methods are written out in Ruby, the latest one wins out, but just wondering how it is possible for two methods of the same name to be written in this fashion, without one overwriting the other.

Answer

Because those are two different method names. In ruby it is a idiom that a method name with a = is a assignment method. When the interpretor is parsing the source code it sees the difference between

def noise

and

def noise=

If you were to take out the = in that first noise method you would observe the behavior that you expected. If you are really interested in the ins and outs of how method look up in ruby works (and you should be since its really important for every ruby programmer to know) checkout this post