I'm sure there is a more idiomatic ruby way to write the code below:
@var = obj['blah'] unless obj['blah'].nil?
I've got a whole load of these to do (see below), and there must be a nicer way!
@num_x = obj['num_x'] unless obj['num_x'].nil?
@num_y = obj['num_y'] unless obj['num_y'].nil?
@num_iterations = obj['num_iterations'] unless obj['num_iterations'].nil?
@pe = obj['pe'] unless obj['pe'].nil?
I have a feeling that the ||=
operator may be useful, but can't seem to quite work out how to use it.
Depending on your circumstances, and unless the instance variables already have an existing value that you want to preserve if the value in obj
is nil
then it might not be a problem to just let them be set to nil
.
Alternatively, you could write a little helper function like:
def set_instance_variables_for_non_nil_values(h, *keys)
keys.each do |key|
instance_variable_set "@#{key}", h[key] unless h[key].nil?
end
end
Then in your example code you would use it like this:
set_instance_variables_for_non_nil_values obj, 'num_x', 'num_y',
'num_iterations', 'pe'
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