Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the largest value for an array of hashes with common keys?

Tags:

ruby

I have two arrays, each containing any number of hashes with identical keys but differing values:

ArrayA = [{value: "abcd", value_length: 4, type: 0},{value: "abcdefgh", value_length: 8, type: 1}]
ArrayB = [{value: "ab", value_length: 2, type: 0},{value: "abc", value_length: 3, type: 1}]

Despite having any number, the number of hashes will always be equal.

How could I find the largest :value_length for every hash whose value is of a certain type?

For instance, the largest :value_length for a hash with a :type of 0 would be 4. The largest :value_length for a hash with a :type of 1 would be 8.

I just can't get my head around this problem.

like image 948
Starkers Avatar asked Oct 08 '13 20:10

Starkers


1 Answers

A simple way:

all = ArrayA + ArrayB # Add them together if you want to search both arrays.
all.select{|x| x[:type] == 0}
   .max_by{|x| x[:value_length]}

And if you wanna reuse it just create a function:

def find_max_of_my_array(arr,type)
  arr.select{|x| x[:type] == type}
     .max_by{|x| x[:value_length]}
end

p find_max_of_my_array(ArrayA, 0) # => {:value=>"abcd", :value_length=>4, :type=>0}
like image 98
hirolau Avatar answered Oct 18 '22 19:10

hirolau