Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

ruby - Get min and max value from this array of hashes

I have an array that contains a hash in each row containing created_at and a value. How do I get the min and max from the array for the value fields?

The array is called - channels_counts_for_history_graph

and

channels_counts_for_history_graph.max[1]

Gives me the max date rather than the max value?

[[Sun, 30 Dec 2018 15:03:55 UTC +00:00, 4305],
[Sun, 30 Dec 2018 15:05:42 UTC +00:00, 4305],
[Mon, 31 Dec 2018 09:24:06 UTC +00:00, 4306],
[Sat, 05 Jan 2019 09:04:50 UTC +00:00, 4308],
[Tue, 01 Jan 2019 11:26:04 UTC +00:00, 4306],
[Wed, 02 Jan 2019 17:24:19 UTC +00:00, 4305]]

Any help appreciated.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest using Enumerable#minmax_by to get the min and the max value in just one method call:

array = [['Sun, 30 Dec 2018 15:03:55 UTC +00:00', 4305],['Sun, 30 Dec 2018 15:05:42 UTC +00:00', 4305],['Mon, 31 Dec 2018 09:24:06 UTC +00:00', 4306],['Sat, 05 Jan 2019 09:04:50 UTC +00:00', 4308],['Tue, 01 Jan 2019 11:26:04 UTC +00:00', 4306],['Wed, 02 Jan 2019 17:24:19 UTC +00:00', 4305]]

array.minmax_by(&:last)
#=> [["Sun, 30 Dec 2018 15:03:55 UTC +00:00", 4305], ["Sat, 05 Jan 2019 09:04:50 UTC +00:00", 4308]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...