boulder_ruby
boulder_ruby

Reputation: 39695

A hash using lambdas without relying on conditionals or enumerators

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

Answers (1)

sawa
sawa

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

Related Questions