在Ruby类中实现真实性
问题描述:
Ruby类是否有可能实现一个真实性方法,或者是否所有假对象和nil对象在设计时都会自动为真?
Is it possible for a Ruby class to implement a truthiness method or are all objects beside false and nil automatically true by design?
答
第二个问题的答案是:是的,在Ruby中,除false
和nil
之外的所有内容都被认为是真实的".
The answer to your second question is: yes, everything else than false
and nil
is considered "truthy" in Ruby.
例如,
a = 'foo' if 0
# => "foo"
a = 'foo' if []
# => "foo"
a = 'foo' if ''
# => "foo"
a = 'foo' if nil
# => nil
a = 'foo' if false
# => nil