I just discovered that whitespace inside parens can matter in Ruby in an unexpected way: Here are 3 functions which look semantically identical to me:
def foo(x)
return {
:a => (x - 100),
}
end
def bar(x)
return {
:a => (x
- 100),
}
end
def zot(x)
return {
:a => (x -
100),
}
end
However, foo(10) and zot(10) return {:a=>-90} (as I expected) while bar(10) returns {:a=>-100} (to my dismay and disappointment).
What am I missing here?
It's an unusual case here but I believe what you're seeing is Ruby interpreting that as several consecutive statements and not a single statement. As in it sees that as:
x # Statement 1
-100 # Statement 2
Where the result of that block of code is -100.
In the case of zot you've expressed your intent to continue that line on the next by having a dangling - binary operator:
x - # Statement 1
100 # Statement 1 (cont)
It's worth noting that you can't do this when making method calls:
zot(x
-100 # Syntax error
)
As in that case the argument syntax rules are a lot more strict. Inside a free-form (...) structure you have considerably more latitude.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With