Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby hash add key/value if modifier

Tags:

ruby

hash

I am working with a ruby hash that contains key/value pairs for creating a new subscriber in my MailChimp API.

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

Obviously, I am getting a syntax error of syntax error, unexpected modifier_if... I am basically only wanting to add the mmerge1 based upon the conditional being true.

like image 485
dennismonsewicz Avatar asked Jun 11 '12 20:06

dennismonsewicz


2 Answers

You can't use if that way, inside a hash-initialization block. You'll have to conditionally add the new key/value after initializing the hash:

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

user_information['mmerge1'] = 'Product X' if user.product_name.present?
like image 144
meagar Avatar answered Nov 15 '22 13:11

meagar


user_information = {'fname' => 'hello world'}
user_information.merge!({'mmerge1' => 'Product X'}) if user.product_name.present?
#=> {"fname"=>"hello world", "mmerge1"=>"Product X"}
like image 35
megas Avatar answered Nov 15 '22 12:11

megas