使用最小值和最大值的哈希值

时间:2018-02-28 19:56:59

标签: ruby

试图推出最便宜和最昂贵的产品。但它的工作方式并不像我希望它能以3.99的成绩推出最低和最高的1.89。我很难过我已经尝试过min和max我试过去谷歌,但我没想出任何东西。

This part is the products.txt

    767,POP,1.89
    341,CANDY,3.99
    587,PIZZA,12.99
    453,energy drink,4.00
    hash = {}
files = File.open("products.txt", "r")

files.each_line do |line|
  id, name, price = line.chomp.split(',')
  hash[id] = [name, price]
end

files.close

while true
  print "\n5. View highest-priced product and lowest-priced product
    Choose an option:  "

  options = gets.chomp.to_i

  if options == 5
    hash.each {|key, value|
      puts "#{key} - #{value[0]}, #{value[1]}"
    }
    sorted = hash.sort_by {|product| product[1]}
    puts
    puts "The cheapest product is #{sorted.first}"
    puts "The most expensive product is #{sorted.last}"
  end
end

2 个答案:

答案 0 :(得分:1)

minmax搜索数组中的最小和最大元素并返回它。他们使用其他一些给出错误结果的标准(词典排序)来搜索最小值和最大值。

但是你的哈希条目已经在sorted数组中正确排序,所以只需得到第一个和最后一个元素:

puts "The cheapest product is #{sorted[0].first}"
puts "The most expensive product is #{sorted[-1].last }"

答案 1 :(得分:1)

不确定最新情况,但您的代码对我不起作用。你想做这样的事情:

options = {
    POP: 1.89,
    CANDY: 3.99,
    PIZZA: 12.99,
    energy_drink: 4.00
}

options.each do |key, value|
    puts "#{key} - #{value}, #{value}"
end

sorted = options.sort
puts
puts "The cheapest product is #{ sorted.min_by {| key, value| value } }"
puts "The most expensive product is #{ sorted.max_by {|key, value| value } }"

在阅读了您发布的代码后,我得到了这样的工作:

hash = {}
files = File.open("products.txt", "r")

files.each_line do |line|
  id, name, price = line.chomp.split(',')
  hash[id] = [name, price.to_f]
end

files.close

while true
  print "\n5. View highest-priced product and lowest-priced product
    Choose an option:  "

  options = gets.chomp.to_i

  if options == 5
    hash.each {|key, value|
      puts "#{key} - #{value[0]}, #{value[1]}"
    }
    sorted = hash.sort_by {|product| product[1][1]}.minmax_by { |key , value| value[1]}
    puts
    puts "The cheapest product is #{ sorted.first }"
    puts "The most expensive product is #{sorted.last}"
  end
end