ruby - A hash using lambdas without relying on conditionals or enumerators -
if have list of accepted aliases , root names 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 this:
coloraliases["crimson"] #=> "red"
i'm trying coax behavior so:
basecolor = lambda |str| x = nil coloraliases.each |keys, value| if keys.include?(str) x = value break end end# of coloraliases hash x end
which should work expected.
am wondering if there more elegant ways this, ways not involving conditional blocks or enumerators. ternary operators ok or improve because they're compact still not preferable because they're conditionals.
your hash design wrong. not using in way hash supposed used. 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, get:
coloraliases["crimson"] # => "red"
ruby hash lambda
No comments:
Post a Comment