0

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?

JAMSUPREME
  • 181
  • 9
  • 2
    The most common use of a naked variable is probably as the last line of a method, in order that the method return the value of that variable. – Cary Swoveland Jun 13 '14 at 03:31

3 Answers3

1

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.

Community
  • 1
  • 1
Patrick Collins
  • 10,306
  • 5
  • 30
  • 69
  • More or less what I was looking for. The concept seemed foreign, but I guess this behavior also applies to other languages. Good links, btw. – JAMSUPREME Jun 13 '14 at 03:50
1

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

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).

sawa
  • 165,429
  • 45
  • 277
  • 381