Home > Mobile >  Why is `a => a` different to `a = a` in Ruby?
Why is `a => a` different to `a = a` in Ruby?

Time:06-24

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?

CodePudding user response:

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.

  • Related