the12
the12

Reputation: 2415

How does Ruby distinguish between Method and Method=(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.

Upvotes: 2

Views: 238

Answers (2)

Sagar Pandya
Sagar Pandya

Reputation: 9497

How does Ruby distinguish between noise and noise = (parameter)?

By the fact that they have different names. noise=(parameter) (correctly defined with no spaces and often referred to as a setter method because it sets @noise) is not the same as noise (often referred to as a getter method because it gets @noise).

The = is part of the name of the method. When using = at the end of a method name, you can then call the method with a parameter to set @noise:

animal.noise=('baaaa')

but Ruby's syntactic sugar allows you to simply write.

animal.noise = 'baaaa'

then to to get back the value of @noise we call the noise method:

animal.noise #=> 'baaaa'

Upvotes: 3

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

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

Upvotes: 3

Related Questions