10/20 The Right Tool for the Job


#1

This worked for!

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


10/20 The Right Tool for the Job
#2

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? }

#3

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.


#4

Even, we can do this:

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

Or

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


#5

Oh nice! I'll have to try out the "unless x.odd?" one. Thanks!!


#6

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


#7

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


#8

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


#9

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


#10

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

#11

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?


#12

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!


#13

puts my_array.select(&:even?)

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


#14

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!!


#15

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