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
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
The andand gem provides this functionality.
my_object.andand.name.andand.capitalize()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With