Ruby hash add key / value if modifier

I am working with ruby ​​hash which contains key / value pairs to create a new subscriber in my MailChimp API.

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

Obviously, I get a syntax error syntax error, unexpected modifier_if ... I basically only want to add mmerge1 based on the conditional expression true.

+6
source share
4 answers

You cannot use if in this way inside the hash initialization block. You will have to conditionally add a new key / value after the hash is initialized:

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

If mmerge1 allowed to be nil or an empty string, you can use the ternary operator ?: Inside the hash:

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

If you use a conditional expression for a key, you get a fairly readable syntax and, at most, you need to remove only one item from Hash.

 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 
0
source

Source: https://habr.com/ru/post/917825/


All Articles