我正在使用ruby hash
,其中包含用于在MailChimp API中创建新订阅者的键/值对。
user_information = {
'fname' => 'hello world',
'mmerge1' => 'Product X' if user.product_name.present?
}
显然,我收到syntax error, unexpected modifier_if
的语法错误...我基本上只想根据条件为真添加mmerge1
。
答案 0 :(得分:11)
你不能在哈希初始化块中使用if
。初始化哈希后,您必须有条件地添加新的键/值:
user_information = {
'fname' => 'hello world',
}
user_information['mmerge1'] = 'Product X' if user.product_name.present?
答案 1 :(得分:1)
user_information = {'fname' => 'hello world'}
user_information.merge!({'mmerge1' => 'Product X'}) if user.product_name.present?
#=> {"fname"=>"hello world", "mmerge1"=>"Product X"}
答案 2 :(得分:0)
如果允许mmerge1
为nil
或空字符串,则可以在哈希中使用?:
三元运算符:
user_information = {
'fname' => 'hello world',
'mmerge1' => user.product_name.present? ? 'Product X' : ''
}
答案 3 :(得分:0)
如果你在键上使用条件表达式,你会得到一个相当可读的语法,并且最多只需要从哈希中删除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