Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何引用数组中创建的hash.values_Arrays_Ruby_Hash - Fatal编程技术网

Arrays 如何引用数组中创建的hash.values

Arrays 如何引用数组中创建的hash.values,arrays,ruby,hash,Arrays,Ruby,Hash,我创建了一个散列的杂货店列表,其中存储了用户输入的项目及其相关的成本 我想添加存储在此哈希中的所有值。我最初的计划是将它们转换成一个数组,然后从那里开始 hash = {} entry = " " while entry != "q" print "Enter your item: " item = gets.chomp print "Enter the associated cost: " cost = gets.chomp.to_f print "Press any

我创建了一个散列的杂货店列表,其中存储了用户输入的项目及其相关的成本

我想添加存储在此哈希中的所有值。我最初的计划是将它们转换成一个数组,然后从那里开始

hash = {}
entry = " "

while entry != "q"
  print "Enter your item: "
  item = gets.chomp

  print "Enter the associated cost: "
  cost = gets.chomp.to_f

  print "Press any key to continue or 'q' to quit: "
  entry = gets.chomp

  hash[item] = cost  
end

puts "Receipt: "
puts "----------"

hash.each do |k,v|
  puts "#{k} costs $#{v}"
end

puts "----------"
puts "subtotal: "
hash.values
如何引用由
hash.values
创建的新数组

我尝试了
数组。注入(0){| sum,x | sum+x}
,但它不起作用,因为它无法识别新创建的数组。

试试这个

subtotal = hash.values.inject(0, :+)
puts subtotal
在您的代码中,您正在退出数组,但没有使用它。

试试这个

subtotal = hash.values.inject(0, :+)
puts subtotal

在您的代码中,您正在对数组进行解压缩,但没有使用它。

从Ruby 2.4开始,您可以使用:


从Ruby 2.4开始,您可以使用:


是的,成功了!谢谢,我会尽快接受你的回答的。我很高兴,先生:)是的,成功了!谢谢,我会尽快接受你的答复,先生:)