While learning Ruby gotchas, I am getting different results with some calculations in IRB:
1-2-7-2 # => -10
1.-2.-7.-2 # => 4
1.-2.-7.-2.-4 # => 8
1.-2.-7.-2.+4 # => 0
1.-(2).-(7).-(2) # => -10
Possibly it is related to methods and arguments? I am trying to wrap my head around this.
You've chosen an interesting way to approach calculations.
I guess you are trying to omit zeros in your expression 1.-2.-7.-2
which will return -10
if you write it as 1.0 - 2.0 - 7.0 - 2
.
The way you're getting 4
is because 1.-
construction calls -()
method because everything is an object in Ruby and then you pass an argument to the function.
In your case it will be parsed as
1.-( 2.-( 7.-(2) ) )
# if we try to unwrap
a = 7.-(2) # => 5
b = 2.-(a) # => -3
1.-(-3) # (or 1 + 3) => 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.