I accidentally created following check, that works fine, but I’m curious why 🙂
- First of all, I know I can assign
:ainstead of ‘a’ 😉 - I know the right formula for this check, I’m just curious why this works
- I don’t care about optimizing this (read 2)
if params['a'] < 0 || params['a'] > params['b || params[:b] < 1]
Why this works, if there is no closing after ['b.
Apart from this everything works fine, until I remove last ], or change it to something else.
UPDATE:
Here is output from ruby:
irb> params
=> {"a"=>3, "id2"=>"2", "b"=>2, "id"=>"1", :id=>"2"}
irb> if params['a'] < 0 || params['a'] > params['b' || params[:b] < 1]
irb> puts 'strange...'
irb> end
strange...
=> nil
Well, it certainly looks like you have an open quote which gets closed somewhere else, later down the road, on some other line.
Fun fact:
Works. Because it’s just a string key. So you’re just evaluating a huge long string as a key to to the ‘params’ hash which is most certainly going to evaluate to nil because it’s not an existing key in the hash.
Edit!
You edited the question and gave more information. Let’s break this down.
If!
That means, of course: if the value of ” a ” in params is less than 0
… That means ‘or’
Stopping here for a sec – if the value of ‘a’ is greater than….
Wait, what? Let’s look deeper.
So the magic is :
We want the result of the OR statement between :
So what is really happening? Well, in truth, since ‘b’ is not false, it will just return the value of params[‘b’], so this is what your if statement really is:
If ‘b’ evaluated to false for whatever reason, you would end up with “params[params[b:] < 1]” which in your case would be false and would then means “params[false].
Does this make sense?