Try it Out! - Loops and Iterators - Ruby


#1

I am doing the currently excercise said up there. But I couldn't get past it. This is what I tried:

odds = [1, 2, 3, 4, 5]

odds.each do |item|
    items = odds * 2
    print items
end

Please reply if you have found the solution. I would appreciate it. Thank you.

More imformation?
When I did it: it says:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5][1, 2, 3, 4, 5, 1, 2, 3, 4, 5][1, 2, 3, 4, 5, 1, 2, 3, 4, 5][1, 2, 3, 4, 5, 1, 2, 3, 4, 5][1, 2, 3, 4, 5, 1, 2, 3, 4, 5][1, 2, 3, 4, 5]
so I still don't get it.


#2

Let's review your block
odds.each do |item| => Off to a great start!
items = odds * 2
=> The trouble begins. you took each number in odds and started calling them item in the previous line. Here in this line you created a new variable called items and set it equal to two odds.
Thats why you see that unexpected outcome. Ruby literally created two odds( [1,2,3,4,5] , [1,2,3,4,5] ) Just like you asked.
Drops the 's' in 'items' however and we are back on track.

I'm assuming you want your output to be " 2 , 4, 6, 8, 10 "
You won't get that by setting item = odds * 2
Rather you'd want item to now equal item * 2

I think you may be confusing yourself with how you name your variables.
Having an array of numbers called odds...even though it has even numbers in it, seems odd to me.

You're on the right track of things, It takes a while to start thinking like a computer. Luckily Ruby is very forgiving!


#3

i am also stuck on this any help!

odds = [1,3,5,7,9]

odds.each do |i|
    i * 2
    print "#{odds}"
end

#4

You want I to equal i * 2
i = i * 2 or i*= 2 do this

You also don't want to print odds, you want to print your alteration to odds.
Try print i

Blocks can be very confusing
Mess around and keep at it.

Try using IRB, it is your friend.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.