Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If hash has key, use it. Otherwise, use different key

response is a hash that could look like one of two things:

response = {'demo' => 'nil', 'test_01' => 'Demo Data'}

or

response = {'test' => 'Demo Data', 'demo' => 'nil'}

I want to do something like this:

if response.has_key? 'test_01'
    new_response.update(:nps_score  => response['test_01']
else
    new_response.update(:nps_score  => response['test']
end

Is there a more "Ruby" approach to this? Maybe something using the || operator? I am using ruby 2.0.0 and rails 4.0.0.

like image 515
Luigi Avatar asked Mar 21 '14 19:03

Luigi


2 Answers

This is what Hash's #fetch method is for.

new_response.update(nps_score: response.fetch('test_01', response['test']))
like image 155
Chuck Avatar answered Oct 31 '22 19:10

Chuck


new_response.update(:nps_score => response['test_01'] || response['test'])

This will work unless false or nil is a valid value you may be expecting. If that's the case, you can use a ternary.

new_response.update(:nps_score => response.has_key?('test_01') ? response['test_01'] : response['test'])
like image 2
Alex Wayne Avatar answered Oct 31 '22 20:10

Alex Wayne