10/20 The Right Tool for the Job

This worked for!

2.times { puts [1, 4, 6, 8, 10]: }

to evaluate for even numbers using only one liner if

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each { |x| puts x if x.even? }

I like dale2040’s answer. Very nice. If you don’t want to use .even? you could do this too:

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

May be less efficient though.


Even, we can do this:

my_array.each { |x| puts x unless x.odd?}


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


Oh nice! I’ll have to try out the “unless x.odd?” one. Thanks!!

I had almost the same code as you but I had put IF on a beginning and that gave me a syntax error …

this is the answer I got, dale’s is more efficient. I wasn’t aware or forgot about the simpler “.even” tool.

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

my_array.each {|element| puts element if element % 2 == 0}

I used this and it worked, but to me it seems weired and also there was some syntax error

if x % 2 == 0 puts x

Yeah I used:

if my_array % 2 == 0 puts my_array

And it allowed me to pass, but also gave me a syntax error:

(ruby):2: syntax error, unexpected tIDENTIFIER, expecting keyword_then or ‘;’ or ‘\n’
if my_array % 2 == 0 puts my_array

Anyone able to shed any light here?

Replying for others, right so this bothered me so did some independent research…

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

Turns out .even? is a Ruby method so saves messing about with modulos… First line basically iterates over each number in the array ( | x | ) and then prints if .even? returns as true.

puts my_array.select(&:even?)

Is a even nicer way to do it, its almost written english! .select iterates over the array and then &:even? finds the little buggers! :slight_smile:

Hope it helps someone!


puts my_array.select(&:even?)

Brilliant, thanks for the tip! This is the kind of stuff that makes me like Ruby even more.

I LOVE THIS!!! This has opened up another part of my thinking process regarding how Ruby works and how there are so many ways to solve problems. systemrockstar68603 you are an awesome beast!!

Can you explain the" %"?
I tried looking it up in the Ruby Glossary, but didn’t find out what it does.