Ruby哈希表添加键/值(如果满足条件)的修改器

7

我正在使用一个ruby 哈希表,其中包含用于在我的MailChimp API中创建新订阅者的键值对。

user_information = {
    'fname' => 'hello world',
    'mmerge1' => 'Product X' if user.product_name.present?
}

显然,我遇到了语法错误syntax error, unexpected modifier_if... 我只想在条件为真时添加mmerge1
4个回答

12

在哈希初始化块中,你不能以那种方式使用if。你需要在初始化哈希之后有条件地添加新的键/值:

user_information = {
    'fname' => 'hello world',
}

user_information['mmerge1'] = 'Product X' if user.product_name.present?

1

如果您在键上使用条件表达式,您将获得一个相当易读的语法,并且最多只需要从哈希中删除1个元素。

product_name = false
extra_name = false

user_information = {
  'fname' => 'hello world',
  product_name ? :mmerge1 : nil => 'Product X',
  extra_name ? :xmerge1 : nil => 'Extra X'
}
user_information.delete nil

p user_information

1
user_information = {'fname' => 'hello world'}
user_information.merge!({'mmerge1' => 'Product X'}) if user.product_name.present?
#=> {"fname"=>"hello world", "mmerge1"=>"Product X"}

1
merge! 对于单个键/值添加了很多不必要的复杂性。 - user229044
1
另一方面,当添加多个值时,merge!非常有用。 - tadman

0
如果允许mmerge1nil或空字符串,你可以在哈希内使用?:三元运算符。
user_information = {
  'fname' => 'hello world',
  'mmerge1' => user.product_name.present? ? 'Product X' : ''
}

你可以将其设置为 nil 并调用 compact,或者执行 reject(&:blank?) - Andrew Marshall
1
许多方法会将键的存在解释为设置该选项,因此这不是一种好的通用实践模式。 - tadman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接