【发布时间】:2021-05-26 04:46:20
【问题描述】:
我正在尝试制作一个图表来显示范围散列中出现的价格计数。
这是使用 Ruby 2.7 的 Ruby on Rails 6 应用程序。
我有两种方法,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 hash 中指定范围内的价格计数?
我如何得到这个最终结果?
89..201 => 2
202..314 => 2
315..427 => 0
428..540 => 0
541..568 => 1
【问题讨论】:
标签: arrays ruby-on-rails ruby hash