Wednesday, 21 August 2013

Can someone give me a hand with adding my array together? Even with nil as one of the possibilities?

Can someone give me a hand with adding my array together? Even with nil as
one of the possibilities?

I'm teaching myself Ruby before possibly taking an intensive and I'm stuck
on one of my exercises. I would appreciate any help :)
Basically, I'm working with Rspec and am creating a calculator method that
will take an array of numbers and add them together. Since I am a
beginner, I don't want to use inject for this because I haven't learned
'inject' yet.(I've researched this a lot and many of the solutions involve
inject)... I would prefer to start with the basics so I make sure that I
understand the stuff I am learning before moving. So I want to use either
.each or while for this particular exercise.
I've been re-writing this code quite a bit and testing it against the
rspec and I keep running into a problem right off the bat because the
first test consists of the array being empty with nil. I've even tried
doing an if else statement to set nil to 0 if the array is .empty? but
that didn't seem to work.
Here is what I've got right now.
def sum(x)
total = 0
sum.each { |x| total += x}
total
end
It's one of those moments where I really wish I had a teacher in the room
to quickly ask, but I guess that's the downside of starting off teaching
yourself. :)
The rspec is testing an empty array ([]) as well as others that have
multiple integers. Thoughts?

No comments:

Post a Comment