We're supposed to make an array and puts
only even numbers. This is my incorrect code:
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each { |num| num % 2 == 0 ? puts num }
It raises this error:
(ruby):1: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
my_array.each { |num| num % 2 == 0 ? puts num }
Correct, functional code:
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each { |num| puts num unless num % 2 != 0 }
I want to know why code I wrote wouldn't run, even though I know how to write a working version. Does the problem stem from having puts num
in the conditional part of my single line if
statement?