我有一个哈希数组:
using Pkg
给出一定的数量,我想获取arr_of_hsh =[
{minimum_quantity: "250", cost: "1.5600"},
{minimum_quantity: "500", cost: "1.3500"},
{minimum_quantity: "1000", cost: "1.1800"},
{minimum_quantity: "2500", cost: "1.0200"}
]
的值与小于或等于该数量的值最接近的哈希值。例如,如果数量为300,则将返回此哈希:
:minimum_quantity
,如果金额为1000:
{minimum_quantity: "250", cost: "1.5600"}
答案 0 :(得分:3)
保持数据结构不变
arr_of_hsh.select { |item| item[:minimum_quantity].to_i <= quantity }.
max_by { |item| item[:minimum_quantity].to_i }
答案 1 :(得分:1)
这里是单程解决方案。
def f(arr, qty)
h = arr.min_by do |h|
n = h[:minimum_quantity].to_i
n <= qty ? (qty-n) : Float::INFINITY
end
h[:minimum_quantity].to_i <= qty ? h : nil
end
(100..1100).step(100).each { |qty| puts "#{qty}: #{f(arr_of_hsh, qty)}" }
100: nil
200: nil
300: {:minimum_quantity=>"250", :cost=>"1.5600"}
400: {:minimum_quantity=>"250", :cost=>"1.5600"}
500: {:minimum_quantity=>"500", :cost=>"1.3500"}
600: {:minimum_quantity=>"500", :cost=>"1.3500"}
700: {:minimum_quantity=>"500", :cost=>"1.3500"}
800: {:minimum_quantity=>"500", :cost=>"1.3500"}
900: {:minimum_quantity=>"500", :cost=>"1.3500"}
1000: {:minimum_quantity=>"1000", :cost=>"1.1800"}
1100: {:minimum_quantity=>"1000", :cost=>"1.1800"}
如果要为给定的arr_of_hsh
多次调用该方法,请按{em>减小值arr_of_hsh
对arr_by_hsh[:minimum_quantity.to_i
进行排序,然后简单地使用{{3 }}。
def f(arr, qty)
h = arr.find { |h| h[:minimum_quantity].to_i <= qty }
end
arr = arr_of_hsh.sort_by { |h| -h[:minimum_quantity].to_i }
#=> [{:minimum_quantity=>"2500", :cost=>"1.0200"},
# {:minimum_quantity=>"1000", :cost=>"1.1800"},
# {:minimum_quantity=>"500", :cost=>"1.3500"},
# {:minimum_quantity=>"250", :cost=>"1.5600"}]
(100..1100).step(100).each { |qty| puts "#{qty}: #{f(arr, qty)}" }
#=> (same as above)