ruby哈希添加键/值if修饰符
我正在使用一个rubyruby哈希添加键/值if修饰符,ruby,hash,Ruby,Hash,我正在使用一个rubyhash,它包含用于在MailChimp API中创建新订户的键/值对 user_information = { 'fname' => 'hello world', 'mmerge1' => 'Product X' if user.product_name.present? } 显然,我得到了一个语法错误语法错误,如果出现意外的修饰符。。。我基本上只想在条件为true的基础上添加mmerge1。如果那样,在哈希初始化块中不能使用。初始化哈希后,
hash
,它包含用于在MailChimp API中创建新订户的键/值对
user_information = {
'fname' => 'hello world',
'mmerge1' => 'Product X' if user.product_name.present?
}
显然,我得到了一个语法错误
语法错误,如果出现意外的修饰符。。。我基本上只想在条件为true的基础上添加mmerge1
。如果那样,在哈希初始化块中不能使用。初始化哈希后,必须有条件地添加新的键/值:
user_information = {'fname' => 'hello world'}
user_information.merge!({'mmerge1' => 'Product X'}) if user.product_name.present?
#=> {"fname"=>"hello world", "mmerge1"=>"Product X"}
user_information = {
'fname' => 'hello world',
}
user_information['mmerge1'] = 'Product X' if user.product_name.present?
user_information = {
'fname' => 'hello world',
'mmerge1' => user.product_name.present? ? 'Product X' : ''
}
如果mmerge1
允许为nil
或空字符串,则可以在散列中使用?:
三元运算符:
user_information = {
'fname' => 'hello world',
}
user_information['mmerge1'] = 'Product X' if user.product_name.present?
user_information = {
'fname' => 'hello world',
'mmerge1' => user.product_name.present? ? 'Product X' : ''
}
如果在键上使用条件表达式,则会得到一个合理可读的语法,最多只需要从散列中删除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
合并代码>为单个键/值增加了许多不必要的复杂性。另一方面,合并代码>在添加多个值时非常有用。您可以将其设置为nil
并调用compact
,或者执行reject(&:blank?
)操作。许多方法会将键的存在解释为设置该选项,因此在一般实践中,这不是一个好的模式。