Is there an equivalent null prevention on chained

2020-02-07 00:08发布

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

标签: ruby
3条回答
家丑人穷心不美
2楼-- · 2020-02-07 00:32

The andand gem provides this functionality.

my_object.andand.name.andand.capitalize()
查看更多
地球回转人心会变
3楼-- · 2020-02-07 00:49

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

查看更多
Viruses.
4楼-- · 2020-02-07 00:50

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
查看更多
登录 后发表回答