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!
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 &&)
···
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
if (h = hash[:value])
puts h[:left], h[:right]
end
Blessings,
TwP
···
On Feb 12, 2009, at 3:24 PM, Pito Salas wrote:
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