Better way to do this?

P

Pito Salas

Hi,

I seem to be repeating myself in the following little bit:

if (!@options[:namespace].nil?)
namespace_options = @options[:namespace]
root.add_namespace(namespace_options[:namespace],
namespace_options[:value])
end

Can someone show me a way to not repeat options[:namespace] ?

Simpler example of the exact same:

if (!hash[:value].nil?)
h = hash[:value]
puts h[:left], h[:right]
end

Thanks for any tips for writing more idiomatic ruby!
 
J

Joel VanderWerf

Pito said:
Hi,

I seem to be repeating myself in the following little bit:

if (!@options[:namespace].nil?)
namespace_options = @options[:namespace]
root.add_namespace(namespace_options[:namespace],
namespace_options[:value])
end

Can someone show me a way to not repeat options[:namespace] ?

Simpler example of the exact same:

if (!hash[:value].nil?)
h = hash[:value]
puts h[:left], h[:right]
end

hash = {
:value => {:left => 1, :right => 2}
}

# original:
if (!hash[:value].nil?)
h = hash[:value]
puts h[:left], h[:right]
end

# looking up :value only once
h = hash[:value]
if h ## assuming you don't use false as a value in the hash
puts h[:left], h[:right]
end

# living a little dangerously (assignment in conditional):
if (h = hash[:value])
puts h[:left], h[:right]
end

# more compactly, if you care:
h = hash[:value] and puts h[:left], h[:right]

# the last one depends on 'and' having low precedence (unlike &&)
 
B

Bertram Scharpf

Hi,

Am Freitag, 13. Feb 2009, 07:24:59 +0900 schrieb Pito Salas:
if (!hash[:value].nil?)
h = hash[:value]
puts h[:left], h[:right]
end

Untested:

if (!(h = hash[:value]).nil?)
puts h[:left], h[:right]
end

or

h = hash[:value]
unless h.nil? then
puts h[:left], h[:right]
end

or

h = hash[:value]
h.nil? or puts h[:left], h[:right]

Hope you enjoyed the trip.

Bertram
 
T

Tim Pease

Hi,

I seem to be repeating myself in the following little bit:

if (!@options[:namespace].nil?)
namespace_options = @options[:namespace]
root.add_namespace(namespace_options[:namespace],
namespace_options[:value])
end

Can someone show me a way to not repeat options[:namespace] ?

Simpler example of the exact same:

if (!hash[:value].nil?)
h = hash[:value]
puts h[:left], h[:right]
end

if (h = hash[:value])
puts h[:left], h[:right]
end


Blessings,
TwP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top