Reputation: 39695
If I were to have a list like so of accepted aliases and root names for basic colors:
coloraliases = {
["red", "crimson", "auburn", "rose", "maroon", "burgundy"] => "red",
["blue", "teal", "aqua", "azure", "cobalt"] => "blue",
["green", "emerald", "absinthe", "avocado", "lime"] => "green",
["yellow", "banana", "lemon", "gold", "citrine"] => "yellow"
}
I couldn't just do this:
coloraliases["crimson"]
#=> "red"
I'm trying to coax this behavior like so:
basecolor = lambda do |str|
x = nil
coloraliases.each do |keys, value|
if keys.include?(str)
x = value
break
end
end# of coloraliases hash
x
end
which should work as expected.
Am wondering if there are any more elegant ways to do this, specifically ways not involving conditional blocks or even enumerators. Ternary operators are ok or better because they're compact but still not preferable because they're conditionals.
Upvotes: 0
Views: 52
Reputation: 168101
Your hash design is wrong. You are not using it in a way a hash is supposed to be used. It should be:
coloraliases = {
"red" => "red",
"crimson" => "red",
"auburn" => "red",
"rose" => "red",
"maroon" => "red",
"burgundy" => "red",
"blue" => "blue",
"teal" => "blue",
"aqua" => "blue",
"azure" => "blue",
"cobalt" => "blue",
...
}
And then, you would simply get:
coloraliases["crimson"] # => "red"
Upvotes: 4