Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More idiomatic ruby way to write @var = obj['blah'] unless obj['blah'].nil?

Tags:

idioms

ruby

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.

like image 641
robintw Avatar asked Jul 24 '10 20:07

robintw


1 Answers

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'
like image 106
mikej Avatar answered Sep 21 '22 08:09

mikej