A more idiomatic ruby ​​way is to write @var = obj ['blah'] if obj ['blah']. Nil?

I am sure there is a more idiomatic ruby ​​way to write the code below:

@var = obj['blah'] unless obj['blah'].nil?

I have everything I need to do (see below), and there should be a more enjoyable 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 it may not seem that it works great, how to use it.

+5
source share
4 answers

Depending on your circumstances, and if the instance variables do not already have an existing value that you want to keep, if the value is objequal nil, then it may not be a problem to just set them to nil.

, :

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

:

set_instance_variables_for_non_nil_values obj, 'num_x', 'num_y',
  'num_iterations', 'pe'
+3

, , -

@var = obj['blah'] or @var

obj['blah'] false, .

||= , , .

+2

:

obj['blah'] && var = obj['blah']
+1

@var , nil false,

@var &&= obj['blah']

, , .

:

obj = {:num_x => 23, :num_y => 75, :pe => 99}

locals = {:num_x => 1, :num_y => 2, :num_iterations => 3, :pe => 4}

puts locals.inspect #=> {:num_y=>2, :pe=>4, :num_iterations=>3, :num_x=>1}

locals.merge! obj

puts locals.inspect #=> {:num_y=>75, :pe=>99, :num_iterations=>3, :num_x=>23}

, .

0

All Articles