10. The right tool for the job --- where have I gone wrong?


#1

Where have I gone wrong with the below code?

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each { |x| if (x % 2 == 0) then puts x }

This is the error message I get:


(ruby):1: syntax error, unexpected '}', expecting keyword_end


#2

Can you think of a simpler way to express this?


#3

I have just realized that I didn't need the if statement here.

So I've changed that to:

my_array.each { |x| puts x % 2 == 0 }

However this still throws an error message saying: Opps, try again!
It works, but why is it still faulty?


#4

Is it printing only even numbers?


#5

It's printing

true
false
true
etc.

How can I fix it so it prints the integers instead of the statements?


#6

Notice that your expression is a boolean? That's why it's printing them.

You still need a conditional, but you are on the right track.

action  IF  condition

#7

Ahh, I've got it now!

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each { |x| puts x if (x % 2 == 0) }

I had it mixed up the wrong way round.


#8

I used this one.

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

my_array.each {|x| puts x if (x.even?) }


#9