这是我正在尝试做的事情:
val1 = [26, 27, 24, 25, 29, 28]
val2 = [17, 20, 22, 21]
val3 = [36, 33, 31, 29]
val4 = [20, 18, 17, 22, 21, 23]
vals = {val1, val2, val3, val4}
sum = 0
count = 0
vals.each do |val|
for i in 0..val.size-1 do
#sum += val[i]
p val[i]
++count
end
end
puts sum
puts count
最初我想得到总和和数,但这不起作用,所以我尝试打印。我可以看到val[i]
无法正常工作。我试过这样做:
vals.each do |val|
aux = val.to_a
for i in 0..aux.size-1 do
p aux[i]
++count
end
end
但它有相同的结果。我还在努力学习基础知识,所以我真的不知道现在要做什么。
答案 0 :(得分:6)
来吧伙计这是Ruby!
val1 = [26, 27, 24, 25, 29, 28]
val2 = [17, 20, 22, 21]
val3 = [36, 33, 31, 29]
val4 = [20, 18, 17, 22, 21, 23]
vals = [val1, val2, val3, val4]
得到总和......
vals.flatten.sum
=> 489
要计算......
vals.flatten.count
=> 20
如果你愿意的话,你甚至可以用散列将它们都返回......
vals.flatten.instance_eval { {:count => count, :sum => sum}}
=> {:count=>20, :sum=>489}
答案 1 :(得分:5)
val1 = [26, 27, 24, 25, 29, 28]
val2 = [17, 20, 22, 21]
val3 = [36, 33, 31, 29]
val4 = [20, 18, 17, 22, 21, 23]
vals = [val1, val2, val3, val4]
sum = 0
count = 0
vals.each do |val|
for i in 0...val.size do
sum += val[i]
p val[i]
count += 1
end
end
puts sum
puts count
这很有效。 {}
不是列表,[]
实际上是一个列表。当您编写{val1, val2, val3, val4}
时,您创建了一个散列关联数组,其中val1和val3为键,val2和val4为值。 val
将以[val1, val2]
形式出现,难怪你无法总结。
顺便说一句,你可以在数组中使用...size
而不是..size-1
。但val.each
仍然会更好。