1

I understand why a = a in Ruby produces nil (see Why is a = a nil in Ruby?).

But using the rightwards assignment operator, a => a produces an error:

irb(main):001:0> a => a
(irb):1:in `<main>': undefined local variable or method `a' for main:Object (NameError)

But when the right hand side is not a complex pattern, I thought => should be exactly the same as =, just flipped.

So why does a => a not behave the same as a = a?

pxeger
  • 148
  • 1
  • 12
  • Probably because the parser is reading from left-to-right, and so it's now trying to **evaluate** `a` *before* it's trying to **assign** `a`. But I'd need to dig deep into ruby source code for absolute certainty on the explanation. – Tom Lord Jun 23 '22 at 11:55
  • 1
    But it doesn't really matter, because this is a very weird thing to write in the code. I don't expect you will ever need to write code like this. (And nor should you ever need to write `a=a`! If you want to initialise `a` as `nil`, then why not put `a = nil` or `nil => a`?) – Tom Lord Jun 23 '22 at 11:56
  • 1
    Honestly, I wouldn't mind at all if `a = a` would raise a `NameError` too :-) – Stefan Jun 23 '22 at 12:39

1 Answers1

2

From the pattern matching docs we know that:

<expression> in <pattern> is the same as case <expression>; in <pattern>; true; else false; end.

so:

a in a

is actually a shorthand for:

case a
in a
  true
else
  false
end

In the above case expression it's probably obvious that you would get a NameError on the very first line.

I assume a => a behaves similarly to a in a in regards to evaluation order.

Stefan
  • 109,145
  • 14
  • 143
  • 218