我经常写下这样的话:
val if val && !val.empty?
我可以更简洁地将此语法定义为:
val if_any
或
val if any
答案 0 :(得分:4)
有val.blank?
irb(main):008:0> ''.blank?
=> true
irb(main):009:0> ' '.blank?
=> true
irb(main):010:0> nil.blank?
=> true
irb(main):011:0> false.blank?
=> true
irb(main):012:0> 'whatever'.blank?
=> false
答案 1 :(得分:2)
不,我不相信Ruby允许你以这种方式扩展语法。最接近的是向Object添加一个方法:
class Object
def any?
!!self && !self.empty?
end
end
"hi".any? # => true
[].any? # => false
nil.any? # => false
if x.any?
# do something
end
答案 2 :(得分:1)
Object方法稍有变化,返回实际值。
class Object
def if_any?
self if self && (!self.respond_to?(:empty?) || !self.empty?)
end
end
[].if_any? # => nil
[42].if_any? # => [42]
"".if_any? # => nil
"hi".if_any? # => "hi"
# and for the objects that don't define #empty?
nil.if_any? # => nil
42.if_any? # => 42
false.if_any? # => nil
true.if_any? # => true
编辑:嗯,再看一遍之后,我想我不会在方法名称中使用问号,因为它违背了返回布尔值的ruby约定。