Sreeraj Sreeraj - 4 months ago 12
Ruby Question

How do i reduce the following code to one line in Ruby?

How do i reduce the following code to one line in Ruby?

unless(current_facebook_user.nil?)
unless(current_facebook_user.client.nil?)
unless(current_facebook_user.client.default_params.nil?)
val = current_facebook_user.client.default_params
end
end
end

Answer

You can using the try() method from active_support/core_ext/object/try.rb introduced since Rails 2.3.2

val = current_facebook_user.try(:client).try(:default_params)

Method Try

Or directly using Safe navigation operator introduced since Ruby 2.3.0

val = current_facebook_user&.client&.default_params

documented here

more on Safe navigation operator