开发者

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


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


Use || operator in one unless: val = ... unless cond1 || cond2 || cond3

Or use && on negations of the conditions in if: val = ... if !cond1 && !cond2


You may not need the third check, as if .default_params is nil, val will be evaluated nil too (if it started nil, this is no problem; if it was already populated, you might want to keep the third guard there :-)

val = current_facebook_user.client.default_params if current_facebook_user && current_facebook_user.client && current_facebook_user.client.default_params


val = current_facebook_user.client.default_params unless current_facebook_user.nil? or current_facebook_user.client.nil? or current_facebook_user.client.default_params.nil?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜