the12 the12 - 5 days ago 4x
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

def noise

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

animal2 =
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.


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


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