tags:

views:

60

answers:

2

Here's what I'm trying to do:

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

Initially I wanted to just get sum and count, but that wasn't working so I tried printing. I can see that the val[i] isn't working as I intended though. I tried doing this:

vals.each do |val|
  aux = val.to_a
  for i in 0..aux.size-1 do
    p aux[i]
    ++count
  end
end

But it had the same results. I'm still trying to learn the basics, so I really have no idea what to do now.

+5  A: 

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

This works. {} is not a list, [] is actually a list. When you write {val1, val2, val3, val4} you have created a hash, associative array, with val1 and val3 as keys and val2 and val4 as values. val would be in [val1, val2] form, no wonder you can't sum that up.

BTW, you can use ...size instead of ..size-1 in arrays. But val.each will still be better.

vava
Also, ++count does nothing. You want count += 1. See: http://ruby-doc.org/docs/Newcomers/ruby.html#operators
jakebman
@jakebman, thanks, it was quite a mistake.
vava
+6  A: 

Come on guys this is 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]

To get the sum...

vals.flatten.sum
=> 489

To get the count...

vals.flatten.count
=> 20

You could even return them both in a hash if you wanted...

vals.flatten.instance_eval { {:count => count, :sum => sum}}
=> {:count=>20, :sum=>489}
Beerlington
Yes, but we must also show what went wrong, and if possible, explain it. If we only answer with this, he will never learn to fix his own mistakes. "The way of the zen cannot be taught - it can only be learned" - Confuscius.
jakebman
Ruby doesn't have a sum method (unless, of course, you define one or use a library that defines one (like e.g. active_support)). Best you can do in plain ruby is `inject(:+)`
sepp2k
Come to think of it, I'm pretty sure `.count` isn't available in 1.8.6 or earlier ;) I was in the Rails console instead of irb when I wrote that. `.size` is a safer bet.
Beerlington