我意外地创建了以下检查,工作正常,但我很好奇为什么:)
:a
而不是'a';)if params['a'] < 0 || params['a'] > params['b || params[:b] < 1]
为什么会这样,如果在['b
之后没有关闭。
除此之外一切正常,直到我删除上一个]
,或将其更改为其他内容。
更新:
以下是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
答案 0 :(得分:1)
嗯,看起来你的公开报价肯定会在其他地方关闭,后来在其他路线上关闭。
有趣的事实:
ruby_hash = {}
ruby_hash['class Atom
def initialize
end
end'] = 0
作品。因为它只是一个字符串键。所以你只是将一个巨大的长字符串作为'params'散列的关键,它肯定会评估为 nil ,因为它不是散列中的现有键。
编辑! 您编辑了问题并提供了更多信息。让我们打破这个。
params = {"a"=>3, "id2"=>"2", "b"=>2, "id"=>"1", :id=>"2"}
# Simple enough, nothing strange here.
if params['a'] < 0 || params['a'] > params['b' || params[:b] < 1]
puts 'strange...'
end
The plot thickens, or does it?
如果!
params['a'] < 0
这当然意味着:如果params中“a”的值小于0
||
......这意味着'或'
params['a'] >
如果'a'的值大于......
,请在此处停止一秒params['b' || params[:b] < 1]
等等,什么?让我们看一下。
params[ => We look inside the hash
'b' || params[:b] < 1 ## HERE IS THE 'MAGIC' => 'b' || params[:b] < 1
] # end of the key
所以神奇的是: 我们希望OR语句的结果在:
之间那真的发生了什么?嗯,实际上,因为'b'不是假的,它只会返回params ['b']的值,所以这就是你的if语句真的是:
if params['a'] < 0 || params['a'] > params['b']
如果'b'因任何原因被评估为假,你最终会得到“params [params [b:]&lt; 1]”,在你的情况下这将是假的,然后意味着“params [false]。< / p>
这有意义吗?