2

? and ! are used in method names, but apparently cannot be used in variable names?

foo! = 2
=> SyntaxError: (irb):1: syntax error, unexpected '='

What is the reason?

B Seven
  • 44,484
  • 66
  • 240
  • 385
  • 10
    Because Ruby's syntax says so. The reason of that (in case it's not clear) isn't a question for SO :) – Adriano Repetti Jun 30 '13 at 17:34
  • 2
    Duplicate of http://stackoverflow.com/questions/5448938/in-ruby-a-variable-name-cannot-end-with-such-as-has-completed-but-a-meth?rq=1 – sawa Jun 30 '13 at 17:49
  • @sawa - Thanks for the helpful and interesting link. I wonder why when I search SO for something I don't find it, and others apparently do. – B Seven Jun 30 '13 at 19:42

1 Answers1

3

? and ! are ruby operators, so they are not allowed in variable names. Otherwise, how will Ruby evaluate something like if (v!=2) (expression that checks whether a variable v is not equal to 2) or something like v?1:0 (expression that will return 1 if v is truthy and 0 if its falsy)

UPDATE Another plausible reason is that Ruby treats names ending with ? and ! as methods

Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • 4
    So why is it legal to call a method `v!`? Would that not cause the same problem? – Frederick Cheung Jun 30 '13 at 17:59
  • I guess the interpreter does not face the same dilemma when dealing with function names, hence, function names can contain ? and !. I believe it has something to do with function calling syntax and function is typicallly on RHS of expression – Wand Maker Jun 30 '13 at 18:04
  • 5
    it's exactly the same dilemma with functions, so this answer doesn't make any sense. – Karoly Horvath Jun 30 '13 at 18:13
  • Give an example where such dilemma can occur with functions. If you extend the question to mean "Why a variable cannot end with =, +, -, *, etc.", my answer still holds good. – Wand Maker Jun 30 '13 at 18:20
  • 3
    `arr.empty ? fn : a` is something different than `arr.empty? fn :a` . The former will call `arr.empty` and switch on its results. The latter will call `fn` with the argument `:a` and then send the results to `arr.empty?`. – John Dvorak Jun 30 '13 at 18:33
  • Only other reason I can see for ? and ! not allowed in variable names is because these are allowed to be last character in function names to offer syntactic sugar. – Wand Maker Jun 30 '13 at 18:42