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.
This is what Hash's #fetch
method is for.
new_response.update(nps_score: response.fetch('test_01', response['test']))
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With