Help DRY a couple ifs

The following snippet is simply nasty, but I
can’t see a simple way to DRY it:

if data[‘medium’].has_key? xyz
medium = data[‘medium’][xyz]
else
$stderr.print "Warning: Did not locate point in medium mesh: "
$stderr.puts xyz.join(’,’)
next
end
if data[‘fine’].has_key? xyz
fine = data[‘fine’][xyz]
else
$stderr.print "Warning: Did not locate point in fine mesh: "
$stderr.puts xyz.join(’,’)
next
end

I suspect my lack of eval knowledge may be
the trouble, but that may be a good thing?

Thanks,

On Jan 28, 2007, at 5:30 PM, Bil K. wrote:

The following snippet is simply nasty, but I
can’t see a simple way to DRY it:

Create an outer loop that has “fine” and “medium”, and plug that in
to your if blocks.

Also, please consider renaming your variable “data”. See http://

the_worlds_two_worst_variable.html for why.

xoxo,
Andy

You could change it like that:

def locate_point(mesh, type, xyz)
point = nil
if mesh[type].has_key? xyz
point = mesh[type][xyz]
else
$stderr.print "Warning: Did not locate point in #{type} mesh: "
$stderr.puts xyz.join(’,’)
end
point
end


next unless medium_point = locate_point(mesh,‘medium’, xyz)
next unless fine_point = locate_point(mesh,‘fine’, xyz)

Cedric

On Jan 28, 5:27 pm, Bil K. [email protected] wrote:

if data[‘fine’].has_key? xyz
Thanks,

Bil K.http://fun3d.larc.nasa.gov

If the hash isn’t autovivifying (if refering to a non-existant entry
won’t create an entry):

medium = data[‘medium’][xyz] or
( $stderr.print "Warning: Did not locate point in medium mesh: "
$stderr.puts xyz.join(‘,’)
next )

Andy L. wrote:

Create an outer loop that has “fine” and “medium”, and plug that in to
your if blocks.

Sure, but how do you get medium and fine as variable names?

Also, please consider renaming your variable “data”. See
O'Reilly Media - Technology and Business Training
for why.

:slight_smile:

Later,

On 1/29/07, Bil K. [email protected] wrote:

Andy L. wrote:

Create an outer loop that has “fine” and “medium”, and plug that in to
your if blocks.

Sure, but how do you get medium and fine as variable names.
:slight_smile:

If you can afford them to become instance variables use

instance_variable_set( symbol, object )

Then your method can become
xyz = a key
[:medium, :fine].each do |type|
if data[type].has_key? xyz
instance_variable_set( “@#{type}”.to_sym, data[type] )
else
@stderr.print "Warning: Did not locate point in #{type} mesh: "
@stderr.puts xyz.join( ‘,’ )
end
end

But I do like Cédric’s response better.