Friday, April 15, 2016

ruby calling methods without parentheses can be misleading

This one stayed in my draft for an year maybe. Thought to add a short explanation and publish it.
[1] pry(main)> class Test
[1] pry(main)*   def gah
[1] pry(main)*     puts "gah"
[1] pry(main)*   end 
[1] pry(main)*   def fah
[1] pry(main)*     gah
[1] pry(main)*     puts gah
[1] pry(main)*     gah="now local variable"
[1] pry(main)*     puts gah
[1] pry(main)*     gah()
[1] pry(main)*   end 
[1] pry(main)* end 

[3] pry(main)> Test.new.fah
gah
gah

now local variable
gah
Basically, if for some reason a variable is defined in current context with the same name as a method, then calling that method later, may result in using the variable instead of the method.

Calling `gah` in the beginning  results in calling the instance method `#gah`. But after we do `gah="now local variable"` then calling `gah` results in obtaining the local variable `gah` value. Finally calling `gah()` always results in calling the instance method.

Simple thing but can be confusing. Solution would be to always call methods using parentheses or make your methods short to easily spot any such mistakes.

My initial reaction when I first learn you can call methods without parentheses in ruby  was that it is a bad idea. Then I became lazy and stopped using them. How can we be so lazy? Only 2 characters? Oddly enough I don't feel like starting to write parentheses again.

No comments:

Post a Comment