0

Possible Duplicate:
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?

Is there any syntactic sugar, in Ruby, that help avoiding "undefined method `xx' for nil:NilClass" without writing this?

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

in Groovy I'll do this

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

Is there an equivalent syntax for Ruby?

Community
  • 1
  • 1
  • Also http://stackoverflow.com/questions/11164004/does-ruby-have-syntax-for-safe-navigation-operator-of-nil-values-like-in-groovy from 4 days ago – tim_yates Jun 27 '12 at 10:28
  • Thanks, it was hard to search in the tons of Ruby questions... –  Jun 27 '12 at 10:43
  • also http://stackoverflow.com/questions/5429790/is-there-a-clean-way-to-avoid-calling-a-method-on-nil-in-a-nested-params-hash. In a nutshell: `andand` or `maybe` (ick). – tokland Jun 27 '12 at 12:15

2 Answers2

1

It's a duplicate question, but I can't find that for the moment. My way is:

if a = something and a = a.very and a = a.long and a = a.to
  if a = a.write
    ...
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381
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

Then in your case

if result = something.try(:very).try(:long).try(:to).try(:write)
  if result != 0
  end
end 
Yuri Barbashov
  • 5,407
  • 1
  • 24
  • 20