Tintin81
Tintin81

Reputation: 10207

How to get hash key from hash with nested arrays?

In my Ruby on Rails app I have this hash with nested arrays in it:

COLORS = {
  :red    => %w(draft open deactivated),
  :green  => %w(sent downloaded paid activated)
}

Is there a way to submit an array value like draft to get the corresponding hash key?

lookup_hash("draft") # => :red

Thanks for any help.

Upvotes: 1

Views: 84

Answers (2)

lobati
lobati

Reputation: 10195

Another thought is to invert the hash for clearer code:

STATUS_COLORS = {
  draft: :red,
  open: :red,
  deactivated: :red,
  sent: :green,
  downloaded: :green,
  paid: :green,
  activated: :green,
}

Then you just do STATUS_COLORS.fetch(status.to_sym). It's a little more verbose, but the code that accesses it is a little more readable.

Upvotes: 3

Ursus
Ursus

Reputation: 30056

What if the given element is present in more than one array? If that is not a problem

def lookup_hash(item)
  COLORS.find { |k, v| v.include?(item) }&.first
end

Upvotes: 2

Related Questions