ToddT
ToddT

Reputation: 3258

Use max_by in Ruby to find the key for the maximum number in a hash

I need to find the category, within an array, that holds the "largest" weight. I define the weights in an environment variable:

CATEGORY_WEIGHTS = {
  "small_standard": 0,
  "large_standard": 1,
  "small_oversize": 2,
  "medium_oversize": 3,
  "large_oversize": 4
}

In this example, the "largest" weighted category would be large_oversize.

The array that I'm checking looks like this:

categories = [
  "small_oversize",
  "large_standard",
  "small_standard",
  "large_oversize"
]

But when I do this, it doesn't return the correct value:

max_category = categories.max_by{ |cat| CATEGORY_WEIGHTS[cat] }

It returns small_oversize instead of large_oversize.

Where did I go astray?

Upvotes: 1

Views: 1308

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

You're using symbols in the hash, but you're trying to access it with strings. Change it to:

max_category = categories.max_by{|cat| CATEGORY_WEIGHTS[cat.to_sym]}

And here is how you can do it simpler:

category_weights = {
  small_standard: 0,
  large_standard: 1,
  small_oversize: 2,
  medium_oversize: 3,
  large_oversize: 4
}

category = category_weights.max_by{|c, w| w}[0]

Upvotes: 5

Related Questions