Dominic Goulet
Dominic Goulet

Reputation: 8113

What happens with this method name/local variable mixing?

I have spotted a method in some code that does the following :

def method1
  method1 = [1, 2, 2, 3, 4, 5, 5]
  return method1.uniq!
end

How does ruby handle this? I know this is bad code, but how does the ruby know what to do with 'method1.uniq!' ? Should it use the method, or the local variable?

Thanks

Upvotes: 4

Views: 723

Answers (2)

Andrew Grimm
Andrew Grimm

Reputation: 81520

If you do defined?(method1) it will tell you that there is a local variable method1 and if you do defined?(method1()) it will say that there is a method method1.

The similarity in syntax between local variables and methods means that when you call a setter method within an object, you have to do self.foo = 42 .

Upvotes: 0

Brett Bender
Brett Bender

Reputation: 19738

You can open a ruby session in a terminal (irb), type in the code in your question, and see the results yourself.

Loading development environment (Rails 3.1.0)
ruby-1.9.2-p290 :001 > def derp
ruby-1.9.2-p290 :002?>   derp = [1,2,3,3,3]
ruby-1.9.2-p290 :003?>   derp.uniq
ruby-1.9.2-p290 :004?>   end
 => nil 
ruby-1.9.2-p290 :005 > derp
 => [1, 2, 3] 

To answer your question, ruby knows the difference between the method derp and the local variable within its scope derp.

Upvotes: 2

Related Questions