简体   繁体   中英

Get the count of values in an array that fall within ranges of a hash in Ruby

I am trying to make a chart that displays the count of prices that occur within a hash of ranges .

This is in a Ruby on Rails 6 app with Ruby 2.7.

I have two methods, sorted_prices and ranges

def sorted_prices
  price_data.sort_by{|e| e['price']}
end

The sorted_prices gives me the following:

[{"price"=>89}, {"price"=>155}, {"price"=>231}, {"price"=>240}, {"price"=>568}] 

I am getting the ranges like this:

def ranges
  range = sorted_prices.first['price']..sorted_prices.last['price']
  range.each_slice(range.last/5).with_index.with_object({}) { |(a,i),h| h[a.first..a.last]=i }
end

ranges gives me the following hash:

{89..201=>0, 202..314=>1, 315..427=>2, 428..540=>3, 541..568=>4}

How can I find the count of prices that fall within the ranges specified in ranges hash?

How do I get this final result?

89..201 => 2
202..314 => 2
315..427 => 0
428..540 => 0 
541..568 => 1
result = ranges.keys.each_with_object({}) do |range, memo|
  count = sorted_prices.count do |price_obj|
    range.cover?(price_obj["price"])
  end
  memo[range] = count
end

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM