12

Groovy:

if there`s my_object -> access 'name' and capitalize

my_object?.name?.capitalize()

What is the equivalent for ruby to avoid a nil object to access attributes with this facility?

Thanks

Luccas
  • 4,078
  • 6
  • 42
  • 72
  • 1
    this is similar http://stackoverflow.com/questions/8721949/simplify-multiple-nil-checking-in-rails/8722096#8722096 – ian Jan 10 '12 at 17:05

3 Answers3

10

This works in Rails:

my_object.try(:name).try(:capitalize)

If you want it to work in Ruby you have to extend Object like this:

class Object
  ##
  #   @person ? @person.name : nil
  # vs
  #   @person.try(:name)
  def try(method)
    send method if respond_to? method
  end
end

Source

In Rails it's implemented like this:

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

class NilClass
  def try(*args)
    nil
  end
end
Mischa
  • 42,876
  • 8
  • 99
  • 111
  • 1
    notably, this is different to `ActiveSupport`'s `Object#try`. `ActiveSupport`'s implementation is basically just `send`, except `nil.try` always returns `nil` – Matthew Rudy Jan 10 '12 at 16:17
  • Thanks @MatthewRudy. This is better since it also accepts blocks and parameters. – Mischa Jan 11 '12 at 00:48
4

The andand gem provides this functionality.

my_object.andand.name.andand.capitalize()
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
-3

Assuming you mean you want to avoid a nil error if my_object is nil. Try :

my_object?.name?.capitalize() unless my_object.nil?

Ruby will do the nil check first and only then try to access the attribute if my_object isn't a null.

Dave

detheridge02
  • 640
  • 1
  • 6
  • 18