(!obj.nil?)链的红宝石语法糖

时间:2012-06-27 10:26:09

标签: ruby groovy null syntactic-sugar null-pointer

  

可能重复:
  Is there a clean way to avoid calling a method on nil in a nested params hash?
  Is there an equivalent null prevention on chained attributes of groovy in ruby?

在Ruby中是否有任何语法糖有助于避免“未定义的方法`xx'为nil:NilClass”而不写这个?

if !something.nil? && !something.very.nil? && !something.very.long.nil? && !something.very.long.to.nil? then
   if something.very.long.to.write != 0 then
    ...
   end
end
在Groovy中

我会这样做

if(something?.very?.loong?.to?.write != 0)

Ruby有相同的语法吗?

2 个答案:

答案 0 :(得分:1)

这是一个重复的问题,但目前我找不到。我的方式是:

if a = something and a = a.very and a = a.long and a = a.to
  if a = a.write
    ...
  end
end

答案 1 :(得分:0)

class Object
  def try(*a, &b)
    if a.empty? && block_given?
      yield self
    else
      __send__(*a, &b)
    end
  end
end

class NillClass
  def try(*args)
    nil
  end
end

然后在你的情况下

if result = something.try(:very).try(:long).try(:to).try(:write)
  if result != 0
  end
end