为什么 `&&` 运算符在哈希块内不起作用,而 `and` 运算符起作用呢?

huangapple go评论64阅读模式
英文:

Why does && operator not work inside a hash block but and operator does?

问题

我想检查所有的值是否为整数且小于10。

第一个使用&&运算符的示例为什么在块内不起作用?这是一个优先级问题吗?

答:第一个示例中的问题是由于 &amp;&amp; 的优先级较低,它被解释为一个整体条件,而不是分别对 is_a? Integer< 10 进行条件检查。因此,它会尝试将整个表达式 value.is_a? Integer &amp;&amp; value &lt; 10 作为一个条件,导致错误。

在第二个示例中,使用 and 运算符可以避免优先级问题,因为它具有较高的优先级,允许按预期方式执行条件检查。

英文:

Given the following hash

hash = {a: 5, b: 10}

I want to check if all values are Integers and < 10.

hash.all?{|key,value| value.is_a? Integer &amp;&amp; value &lt; 10} ## TypeError: class or module required from (pry):3:in `is_a?&#39;

hash.all?{|key,value| value.is_a? Integer and value &lt; 10} ## false

Why does the first example with the &amp;&amp; operator not work inside the block? Is this a precedence issue?

答案1

得分: 4

是的。第一种形式被解释为:

value.is_a?(Integer && (value < 10))

而第二种形式被解释为:

value.is_a?(Integer) and (value < 10)

因此,第一种形式实际上执行了一个意外/不正确的操作 - 要么:

value.is_a?(true)
# 或者
value.is_a?(false)

有很多写法,但我会这样写:

value.is_a?(Integer) && value < 10

总的来说,在像上面这样的复杂语句中完全省略括号会引发问题,我建议避免这样做。很容易陷入像这样的陷阱,导致代码不按照预期顺序执行。

英文:

> Is this a precedence issue?

Yes. The first form is being evaluated like this:

value.is_a?(Integer &amp;&amp; (value &lt; 10))

And the second form is being evaluated like this:

value.is_a?(Integer) and (value &lt; 10)

Therefore the first form is actually running an unexpected/incorrect operation - either:

value.is_a?(true)
# or
value.is_a?(false)

There are many ways to write this, but I would do it as:

value.is_a?(Integer) &amp;&amp; value &lt; 10

In general, completely omitting brackets in complex statements like the above is asking for trouble, and I'd advise avoiding it. It's easy to fall into traps like this, where your code isn't executing in the order you intended.

答案2

得分: 2

&& 的优先级高于 and。这就是为什么我建议使用 && 而不是 and。

你的解决方案是正确的,只需在 Integer 前加上括号 () 并移除空格,即 value.is_a?(Integer)

hash = {a: 5, b: 10}
hash.all?{|key, value| value.is_a?(Integer) && value < 10}

# => false
英文:

&& precedence is higher than and .That's why i will recommend using && instead of and

Your Solution is correct just add braces/parentheses () against Integer and remove the Space i.e value.is_a?(Integer)

hash = {a: 5, b: 10}
hash.all?{|key,value| value.is_a?(Integer) &amp;&amp; value &lt; 10}

#=&gt; false

huangapple
  • 本文由 发表于 2023年2月23日 23:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定