Crystal: The if condition contains multiple local variables that will be overridden by the last value

Created on 12 Mar 2019  Â·  3Comments  Â·  Source: crystal-lang/crystal

Submitting bugs

Sample code:

```` crystal
def positive(v)
if v > 0
v
else
nil
end
end

if v1 = positive(1) && (v2 = positive(2))
puts v1 # => 2
puts v2 # => 2
end
````

You can see that the value of v1 is overwritten by v2. I need to wrap all the conditions in parentheses to avoid this phenomenon. E.g:

crystal if (v1 = positive(1)) && (v2 = positive(2)) puts v1 # => 1 puts v2 # => 2 end

Since the names of the variables are different, this is too much like a trap, isn't it?

Versions

```` bash
➜ ~ crystal --version
Crystal 0.27.2 (2019-02-05)

LLVM: 6.0.1
Default target: x86_64-pc-linux-gnu
````

```` bash
➜ ~ lsb_release -a
LSB Version: 1.4
Distributor ID: Arch
Description: Arch Linux
Release: rolling
Codename: n/a
`````

question

Most helpful comment

Yes, this is how parsing works. Without the parentheses it's parsed as:

v1 = (positive(1) && (v2 = positive(2)))

It's not a bug.

All 3 comments

Yes, this is how parsing works. Without the parentheses it's parsed as:

v1 = (positive(1) && (v2 = positive(2)))

It's not a bug.

We wouldn't want to change the behavior of var = var1 || var2, that is the same as var = (val1 || val2), to be parsed as (var = val1) || val2.

@asterite @j8r

😇 Thank you for your explanation. I understand!

Was this page helpful?
0 / 5 - 0 ratings