Ruby && operator on integers

有些话、适合烂在心里 提交于 2019-12-02 23:43:22

问题


does anyone know the meaning of && and || when applied to integers in Ruby?

Here are some examples in IRB when && and || are applied to integers:

>> 1 && 2
=> 2

>> 2 && 1
=> 1

>> 15 && 20
=> 20

>> 20 && 15
=> 15

>> 0 && -1
=> -1

>> -1 && -2
=> -2

>> 1 || 2
=> 1

>> 2 || 1
=> 2

回答1:


The boolean operators &&, ||, and and or are among the few that are not syntactic sugar for method calls, and thus, there are no different implementations in different classes.

In other words: they behave exactly the same for all objects, i.e. they behave the same for Integers as they do for Strings, Hashes, Floats, Symbols, and any other object.

a && b

evaluates to a if a is falsey (and will not evaluate b at all in this case), otherwise it evaluates to b (and only then will b be evaluated)

a || b

evaluates to a if a is truthy (and will not evaluate b at all in this case), otherwise it evaluates to b (and only then will b be evaluated)

nil and false are falsey, everything else is truthy, including 0, 0.0, '', [], and {}.



来源:https://stackoverflow.com/questions/30478116/ruby-operator-on-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!