Ruby中“and”和&&的区别?

ssm49v7z  于 5个月前  发布在  Ruby
关注(0)|答案(9)|浏览(46)

Ruby中的&&and运算符有何区别?

lkaoscv7

lkaoscv71#

and&&相同,但优先级较低。它们都使用short-circuit evaluation
警告:and甚至比=的优先级更低,所以你通常会想避免and。在Rails指南的“避免双重渲染错误”下可以找到一个应该使用and的例子。

8ulbf1ek

8ulbf1ek2#

实际的区别是结合强度,如果你没有准备好,这可能会导致奇怪的行为:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo

字符串
同样的事情也适用于||or

klh5stk1

klh5stk13#

Ruby Style Guide比我说得更好:
使用&&/||用于布尔表达式和/或控制流。(经验法则:如果必须使用外括号,则使用了错误的运算符。)

# boolean expression
if some_condition && some_other_condition
  do_something
end

# control flow
document.saved? or document.save!

字符串

5lwkijsr

5lwkijsr4#

||&&绑定的优先级与编程语言中布尔运算符的优先级相同(&&的优先级非常高,||的优先级稍低)。
andor具有较低的优先级。
例如,与||不同的是,or的优先级低于=

> a = false || true
 => true 
> a
 => true 
> a = false or true
 => true 
> a
 => false

字符串
同样,与&&不同,and的优先级也低于=

> a = true && false
 => false 
> a
 => false 
> a = true and false
 => false 
> a
 => true


此外,与&&||不同的是,andor具有相同的优先级:

> !puts(1) || !puts(2) && !puts(3)
1
 => true
> !puts(1) or !puts(2) and !puts(3)
1
3
 => true 
> !puts(1) or (!puts(2) and !puts(3))
1
 => true


弱绑定的andor对于控制流可能很有用:请参见http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/。“

jmp7cifd

jmp7cifd5#

and的优先级低于&&
但是对于一个不自负的用户,如果它与其他优先级介于两者之间的运算符沿着使用,例如赋值运算符,可能会出现问题:

def happy?() true; end
def know_it?() true; end

todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"

todo
# => "Clap your hands"

todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"

todo
# => true

字符串

cld4siwp

cld4siwp6#

and的优先级较低,我们通常将其用作控制流修饰符,例如if

next if widget = widgets.pop

字符串
成为

widget = widgets.pop and next


对于or

raise "Not ready!" unless ready_to_rock?


成为

ready_to_rock? or raise "Not ready!"


我更喜欢使用if而不是and,因为if更容易理解,所以我忽略了andor
请参阅“Using “and” and “or” in Ruby“了解更多信息。

d7v8vwbk

d7v8vwbk7#

只检查第一个条件并给出结果,另一方面**&&**强烈检查两个条件并给出逻辑结果。

rqdpfwrv

rqdpfwrv8#

我不知道这是Ruby的意图还是一个bug,但是试试下面的代码。这段代码运行在Ruby 2.5.1版本和Linux系统上。

puts 1 > -1 and 257 < 256
# => false

puts 1 > -1 && 257 < 256
# => true

字符串

dldeef67

dldeef679#

对我来说,如果我想利用条件表达式的副作用,那么and的行为相对于修饰符if更可取-在第一次尝试中观察undefined local variable or method 'y'

km@latika:~$ irb
irb(main):001:0> x=y if (y="hello")
(irb):1: warning: found `= literal' in conditional, should be ==
(irb):1:in `<main>': undefined local variable or method `y' for main:Object (NameError)
        from /usr/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
        from /bin/irb:25:in `load'
        from /bin/irb:25:in `<main>'
irb(main):002:0> quit

字符串
此时y已经被赋值了,所以我重新启动irb来演示我的观点:

km@latika:~$ irb
irb(main):001:0> y="hello" and x=y
=> "hello"
irb(main):002:0> quit


在我看来,这是用非nil(或false,但这不在重点之列)的东西覆盖变量的最好方法。特别是如果我们用complicated_calculation()代替"hello"

相关问题