【问题标题】:Get the count of values in an array that fall within ranges of a hash in Ruby获取数组中落在 Ruby 中哈希范围内的值的计数
【发布时间】:2021-05-26 04:46:20
【问题描述】:

我正在尝试制作一个图表来显示范围散列中出现的价格计数

这是使用 Ruby 2.7 的 Ruby on Rails 6 应用程序。

我有两种方法,sorted_pricesranges

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 2014-01-22
      • 2017-03-21
      • 2014-04-14
      • 2014-10-05
      • 2015-05-29
      • 1970-01-01
      • 2021-02-05
      相关资源
      最近更新 更多