Member-only story

Frequently used Active Support Methods in Ruby on Rails — Part 3

Gokul
4 min readApr 9, 2021

--

👉 try

`try` is closely related to Object#send, in addition to that try will return nil if the field is not reachable.

Without try

unless @data.nil?
@data.value
end
OR@data.value unless @data.nil?

with try

@data.try(:value)

We can use the try with block argument instead of arguments. Which will be executed if the object is not nil

@person.try {|p| "#{p.first_name} #{p.last_name}" }

It’s worth noting that try will ignore no-method errors and return nil instead. Use try! instead, if you want to avoid typos

@data.try(:value)   # => nil
@data.try!(value)…

--

--

Gokul
Gokul

No responses yet