Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How important is whitespace inside parens in Ruby?

Tags:

syntax

ruby

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?

like image 993
sds Avatar asked Apr 17 '26 03:04

sds


1 Answers

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.

like image 78
tadman Avatar answered Apr 19 '26 05:04

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!