I'm using Ruby 2.4. If I want to find the maximum number of a numeric attribute of my model, I can do
max_num = my_objects_arr.maximum(:numeric_attr)
but how would I find the maximum number of attributes whose values occur exactly twice in my array? That is, let's say my objects array has three objects
obj1 - numeric_attr = 3
obj2 - numeric_attr = 3
obj3 - numeric_attr = 4
The maximum of the attributes above that occur exactly twice would be "3". Although "4" is the maximum of all attributes, it only occurs once in the array.
array = [1, 2, 3, 2, 3, 4]
array.group_by { |e| e } # group_by(&:itself) since 2.3
.select { |_, v| v.count == 2 }
.keys
.max
#⇒ 3
For objects and attributes:
my_objects_arr.group_by { |o| o.numeric_attr }
.select { |_, v| v.count == 2 }
.keys
.max
To get the objects themselves:
my_objects_arr.group_by { |o| o.numeric_attr }
.select { |_, v| v.count == 2 }
.max_by(&:first)
.last
Since you are using rails calculations eg #maximum
this should work for you
my_objects_arr
.group(:numeric_attr)
.having("count(numeric_attr) = 2")
.maximum(:numeric_attr)
This will find the maximum value of numeric_attr
by grouping them by the numeric_attr
and selecting the numeric_attr
that have exactly 2
SQL estimation
SELECT
MAX(numeric_attr)
FROM
[SOME TABLE]
GROUP BY
numeric_attr
HAVING
COUNT(numeric_attr) = 2
arr = [1, 2, 3, 2, 3, 4]
arr.each_with_object(Hash.new(0)) {|n,h| h[n] += 1}.select {|_,nbr| nbr == 2}.keys.max
#=> 3
This uses the form of Hash::new that creates a hash h
with a default value of zero. That means that if h
does not have a key k
, h[k]
returns zero (without altering the hash). This refers to the method Hash#[] , not to be confused with Hash#[]= .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.