IRB - Ruby hash syntax 1.9.x: {if: true} not equal {: if => true}

In short, I wrote a method that included an argument of parameters that will do certain things if the value for the key: if, evaluates to true. When I try to use the hash in the IRB using the new syntax, I received a syntax error in the IRB, the prompt remains open:

1.9.3p374 :010 > {if: true} 1.9.3p374 :011?> 

Using the old syntax works fine:

 1.9.3p374 :011 > {:if => true} => {:if=>true} 

All keywords that trigger the statement exhibit the same behavior. For instance. def , do , module , case

Other reserved words that occur in the middle and class work just fine: else , end

My question is: is this expected behavior, error or limitation?

+6
source share
1 answer

It is not easy to reliably and unambiguously disassemble things in any language. This is especially true when you start using reserved words. And irb should go beyond that and provide an interactive model on top of the parser, which is even more complicated. I personally do not think that it is too much to worry about such cases, whether it is a user of the language or an accompanying person. In my opinion, it’s better to just find out what works and, if possible, to avoid getting into these situations.

You can see some similar behaviors in plain Ruby, outside of irb . For instance:

 puts({if: true}) # no problem, behaves as expected in Ruby 1.9.3. puts {if: true} # raises a syntax error in Ruby 1.9.3 

To answer your question is “expected behavior, error or limitation”, I would say that you should ignore irb and compare it with regular Ruby, and if you do, it works fine. This means that it must be an irb error.

But is it possible to solve this? @coreyward makes a remark in his comment that irb should delay execution in most cases when it encounters an if . You should learn further to know exactly, but you may not be able to unambiguously interpret all such cases.

My advice: Avoid this construct at all if you can, and don't use reserved words for shortcuts if you can avoid it!

Here you can run a file with simple Ruby (e.g. MRI). You should see {:if=>true} in the output to confirm that it works.

 {if: true} foo = {if: true} # if MRI is working, should be able to execute this file without trouble. p foo 
+6
source

All Articles