I'm fairly new to Ruby (coming from C#), so I'm wondering why this is valid:
x = 2
x #why is this valid?
Does ruby interpret it as x.inspect or something internally?
I'm fairly new to Ruby (coming from C#), so I'm wondering why this is valid:
x = 2
x #why is this valid?
Does ruby interpret it as x.inspect or something internally?
I believe that Ruby follows the Lisp where expressions return their own value, and, in particular, some expressions are self-evaluating. As a result, return
is actually unnecessary in Ruby.
Why is a variable a valid statement?
Because it isn't a statement, it's an expression. There are no statements in Ruby, everything is an expression.
Does ruby interpret it as
x.inspect
or something internally?
No. x
is interpreted as x
, nothing else.
In a REPL, like IRb or Pry, the REPL may or may not call some methods on the object which is the result of evaluating x
in order to display some human-readable text representation of the object, but that is a) a feature of the REPL, not Ruby and b) applies to all expressions, not just local variable dereferences.
It is valid because x
is a defined variable, i.e., it refers to an object. It doesn't interpret it as x.inspect
or anything else. x
is x
(actually 2
).