The Zen of Ruby


#1

Instructions: Write a loop that only puts the even values of my_array (Bonus points if you use a one-line if statement)

my code:

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

error:

undefined local variable or method `x' for #<Context:0x10c89dc>

any solutions?? :sweat_smile:


#2

Try with the if inside the block...

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

#3

@mtf thanks for the help :smile: It probably never worked because x was locally defined and therefore couldn't be accessed from the outside. So that would mean that x was undefined, this makes perfect sense since it matches the error: undefined local variable or method x