Ruby:将数组插入列表后,如何检索它们并将它们作为数组处理?

时间:2010-03-06 02:05:09

标签: 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}
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

但它有相同的结果。我还在努力学习基础知识,所以我真的不知道现在要做什么。

2 个答案:

答案 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仍然会更好。