ruby 中的 if(!x) 与 if(x==false) [英] if(!x) vs if(x==false) in ruby

查看:35
本文介绍了ruby 中的 if(!x) 与 if(x==false)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白以下代码:

ruby-1.9.1-p378 > puts "nil is false" unless nil
nil is false
 => nil 
ruby-1.9.1-p378 > puts "nil isn't false" unless nil == false
nil isn't false
 => nil 

在大多数语言(至少是基于 C 的语言)中,if(!cond) 和 if(cond==false) 的计算结果相同.是什么让情况并非如此?

In most languages (of a C-base, at least), if(!cond) and if(cond==false) evaluate the same. What's going on here to make that not the case?

(我想知道原因的详细信息,我明白就是这样.)

(I'd like the details of why, I understand that that is how it is.)

推荐答案

Ruby 认为 falsenil 是仅有的两个假"值,而其他一切都是真实".这是根据定义,不能修改(至少在 MRI 中).此定义用于所有内置运算符,例如 ifunlesswhileuntilcond ?if_truthy : if_falsey, ||, &&, ...

Ruby considers that false and nil are the only two "falsy" values, while everything else is "truthy". This is by definition and can not be modified (at least in MRI). This definition is used for all builtin operators like if, unless, while, until, cond ? if_truthy : if_falsey, ||, &&, ...

编写 foo == bar 将始终以 bar 作为参数调用 foo 上的 == 方法.默认情况下,nilfalsetrue 和所有其他立即数(如符号等)仅等于它们自己.不过,这可以改变:

Writing foo == bar will always call the == method on foo with bar as an argument. By default, nil, false, true and all other immediates like symbols, etc..., are only equal to themselves. This could be changed, though:

def nil.==(bar)
  super || bar == false
end
puts "nil == false" if nil == false  # => "nil == false"

在 Ruby 1.9 中,您还可以重新定义运算符 !,因此 unless foo 不一定与 if !foo 或与 if foo 相反:

In Ruby 1.9, you can also redefine the operator !, so unless foo is not necessarily the same as if !foo or the contrary of if foo:

def true.!
  true
end

puts "True?"   if  true # => "True?"
puts "or not?" if !true # => "or not?"

并不是说有人会建议做这样的事情...

Not that anybody would recommend doing anything like this...

这篇关于ruby 中的 if(!x) 与 if(x==false)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆