获取数组中落在 Ruby 中散列范围内的值的计数
Get the count of values in an array that fall within ranges of a hash in Ruby
我正在尝试制作一个图表来显示 散列范围内出现的价格数量。
这是 Ruby 上 Rails 6 应用 Ruby 2.7.
我有两种方法,sorted_prices
和ranges
def sorted_prices
price_data.sort_by{|e| e['price']}
end
sorted_prices
给了我以下信息:
[{"price"=>89}, {"price"=>155}, {"price"=>231}, {"price"=>240}, {"price"=>568}]
我得到这样的范围:
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
给我以下哈希值:
{89..201=>0, 202..314=>1, 315..427=>2, 428..540=>3, 541..568=>4}
如何找到落在 ranges
哈希中指定范围内的价格计数?
如何获得最终结果?
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
我正在尝试制作一个图表来显示 散列范围内出现的价格数量。
这是 Ruby 上 Rails 6 应用 Ruby 2.7.
我有两种方法,sorted_prices
和ranges
def sorted_prices
price_data.sort_by{|e| e['price']}
end
sorted_prices
给了我以下信息:
[{"price"=>89}, {"price"=>155}, {"price"=>231}, {"price"=>240}, {"price"=>568}]
我得到这样的范围:
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
给我以下哈希值:
{89..201=>0, 202..314=>1, 315..427=>2, 428..540=>3, 541..568=>4}
如何找到落在 ranges
哈希中指定范围内的价格计数?
如何获得最终结果?
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