This worked for!
2.times { puts [1, 4, 6, 8, 10]: }
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?}
Or
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!
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.