Rails散列null检查-'if-condition'和'三元运算符'哪个更好?

问题描述 投票:0回答:2

我在哈希下面]

instance_options[:param_page]
instance_options[:param_page][:comment_page]
instance_options[:param_page][:comment_per]

我需要comment_page,comment_per值我做了重构代码但是我不确定什么是最好的哈希空检查让我知道最好的null检查,如果您认识另一个人

之前

comment_page = 1
comment_per = 0
param_page = instance_options[:param_page]
if param_page
  comment_page = param_page[:comment_page].presence || comment_page
  comment_per = param_page[:comment_per].presence || comment_per
end

之后

comment_page = instance_options[:param_page][:comment_page].present? ? instance_options[:param_page][:comment_page] : 1
comment_per = instance_options[:param_page][:comment_per].present? ? instance_options[:param_page][:comment_per] : 10

我在下面有hash instance_options [:param_page] instance_options [:param_page] [:comment_page] instance_options [:param_page] [:comment_per]我需要comment_page,comment_per值,我确实重构了代码...

ruby-on-rails hash null-check
2个回答
1
投票

您可以进一步:

© www.soinside.com 2019 - 2024. All rights reserved.