相关疑难解决方法(0)

Ruby中And/&&的运算符优先级

我对Ruby中的和/ &&/=关键字有疑问.

ruby文档说,所提到的关键字的优先级是:(1)&&,(2)=,(3)和.

我写了这段代码:

def f(n) 
 n
end

if a = f(2) and  b = f(4) then  
    puts "1) #{a} #{b}" 
 end

if a = f(2) &&  b = f(4) then   
    puts "2) #{a} #{b}"     
end
Run Code Online (Sandbox Code Playgroud)

输出是:

1)2 4 [预期]

2)4 4 [ 为什么?]

出于某种原因,使用&&会导致a和b评估为4?

ruby and-operator

14
推荐指数
2
解决办法
5266
查看次数

ruby中的false && nil和nil && false

为什么nil && false返回nilfalse && nil返回false

我在nil ||中读到了最佳答案 假和假|| 在红宝石中没有.在我看来,这两个nilfalse评估为falsy价值,但为什么这两个表达式返回的值不同?

ruby

2
推荐指数
1
解决办法
680
查看次数

标签 统计

ruby ×2

and-operator ×1