Ruby makes it easy to create a lot of functional code in a short period of time. However, there are some instances where you must be explicit and take care to avoid errors.
Local Variables versus Methods
If a local variable exists with the same name as a method, the local variable will be used unless you put parentheses behind the method or use self.methodName.
def colors(arg1="blue", arg2="red")
"#{arg1}, #{arg2}"
end
colors = 6
print colors
The above outputs 6. If you were expecting to use the color method, you might have been surprised. Using parentheses, in this case, would yield the desired result:
def colors(arg1="blue", arg2="red")
"#{arg1}, #{arg2}"
end
colors = 6
print colors("purple", "chartreuse")
This outputs:
purple, chartreuse
More Whitespace Issues
You need to ensure that you use whitespace properly when using methods, as extra whitespace can result in errors.
def countdownLength= length
def countdownLength=(length)
def countdownLength= (length)
def countdownLength= ( length )
The above works fine, while this:
def countdownLength = (length)
results in a parse error, because the whitespace before the equal sign makes it part of the method name.
Block Local Variables
Be careful to keep variables in the scope for which they are intended. Not doing so will yield in unexpected results. Here’s a particularly nasty one:
i = 0
while i < 10
...
[1,2,3].each {|i| ... } # i gets overwritten here
i += 1
end
While we intended the i within the each iterator to stay in its own scope, it actually overwrote the i in the while loop, resulting in an endless loop.