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


#1

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.


#2

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


#3

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!


#4

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.
That
s 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 }


#5

This worked for me, thank you so much!


#6

My solution was bit different:

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

#7

@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:


#8

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


#9

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

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


#10

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


#11

This is what I did and it worked.

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

#12

@lolman is it correct.........:smile:


#13

@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.


#14

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


#15

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