Home > Software design >  Why is x-- a valid ruby statement but it doesn't do anything?
Why is x-- a valid ruby statement but it doesn't do anything?

Time:04-13

I know ruby doesn't support integer increment x or decrement x-- as C does. But when I use it, it doesn't do anything and doesn't throw an error either. Why?

Edit:

Sorry the code I actually found was using --x, which is slightly different, but the question remains: Why?

x = 10
while --x > 0
  y = x
end

CodePudding user response:

Edit: to answer OP's comment about it actually being --x

In Ruby, operators are methods. --x, x , x==, etc all can do wildly different things. -- and are not themselves valid operators. They are combinations of operators.

In the case of your provided code, --x is the same as -(-x).

If x = 5, then -x == -5 and --x == 5.

---x would be -(-(-x)), and so on.


x-- is technically valid, depending on what the next line of code contains.

The following is valid, for example:

  def my_func
    x = 1
    y = 10
    x--
    y
  end

That would get interpreted as x - (-10). The result doesn't get assigned to any value, so the x-- line would appear to do nothing and the function would just return y.

You could even have nil on the last line of the function, and you wouldn't get a syntax error in some tools, but you would get a runtime error when the function is called.

x-- just on its own is not valid. It requires a Numeric argument to follow it. That argument can be on the next line.

CodePudding user response:

But when I use it, it doesn't do anything and doesn't throw an error either.

It does:

ruby -ce 'x--'
# -e:1: syntax error, unexpected end-of-input

x-- is not valid Ruby syntax.

  •  Tags:  
  • ruby
  • Related