Lesson Passes me, but errors in Console. The Zen of Ruby 10/20

THE ZEN OF RUBY 10/20

My code that follows works, but errors in the console log. I tried to have it compile in one line so any number of things could be wrong here.

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

The error I’m receiving for this in the console is:

(ruby):2: syntax error, unexpected '|', expecting '}'
puts my_array.each if {|x| x % 2 }
                        ^
(ruby):2: syntax error, unexpected '}', expecting $end

I’m not particularly fluent with Ruby so if anyone has any ideas please shoot them at me.

Once again I passed the lesson. I would just like to figure out if any of my syntax was incorrect, and how to fix it if it is.

1 Like

If you want learn such things
i would do a google search on a site were a lot of programmers ask-questions / discuss and give opinions.

In your case i would do
ruby array each site:stackoverflow.com

I have the same problem than you, I can pass the lesson but nothing in the console!!
if anyone can help that would be great in order to understant what’really wrong in the code!

Its just your syntax error,but logic is right You call ".each" method for my_array.Example:my_array.each Then you tell ".each" method what to do: for each |x| you puts this value.Example: {|x| puts x}.It prints all values,but we need the even values. Thats why we add if condition: {|x| puts x if x%2==0 },what tell us print our value if it divisible by 2.
P.S.
This is my code
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each {|x| puts x if x%2==0 }

4 Likes

This worked for me, thank you so much!

1 Like

My solution was bit different:

my_array.each { |n| puts n % 2 == 0 ? "#{n}": nil}

@arraycoder47495,
well it is all in your userName… :+1:

maybe you could have explained the functioning of your integrated ternary-operator
so @lolman knows what kind of magic you are using :flashlight:

Is this not specifically where people are supposed to ask questions? hmmmmm

3 Likes

If I may offer an alternative here, this one worked for me:

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

1 Like

I’m sure there are plenty of ways this could have worked. Thank you however for your input!

This is what I did and it worked.

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

@lolman is it correct…:smile:

@abergeron, The solution from @devslayer48819 was the solution I found to be the correct solution to my inquiry. It was also mimicked by @codecoder49931. His solution was the same but confirmed what was known. I’m not sure if your post was supposed to be a question, however if it was I hope that I answered it for you.

one more solution
my_array.each { |x| puts x.even? ? “#{x}”: nil}

After studying your answer it makes so much sense. thank you.