How to find the hash key whose value has the largest number of elements

I am using Ruby 2.4.

I have a hash whose key is a number and whose value is an array of elements. How to find a key in a hash with a value that has most elements? I know that if my value were a single number, I could do this:

my_hash.max_by { |k, v| v }

But since this value is an array, I'm not sure how to say it above to use the number of elements in the array as what should be maxed.

+4
source share
3 answers

max_by - correct method:

my_hash = { a: [1, 2], b: [1, 2, 3], c: [5] }

key, longest_array = my_hash.max_by{ |k, array| array.size }

p key
#=> :b

p longest_array
#=> [1, 2, 3]

You just need to specify on which object the mapping should be. In this case, the size of the array value.

, : , - :size.

+7

:

my_hash.map {|k, v| [k, v.count]}.max_by {|k, v| v}.first

. , - . max_by, . , first .

+1

I'm not sure if I understood your question correctly, but I assume that you have something like this:

my_hash = {1=>[2, 1, 3, 4], 2=>[1, 2], 3=>[1, 4, 6]}

If in this case you can get the key for the largest array, like this:

my_hash.max_by{|k,v| v.count}.first
0
source

Source: https://habr.com/ru/post/1668559/


All Articles