Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Ruby, print even numbers of array

I was doing a simple exercise to output the even numbers in an array. I tried to use a Ruby inline conditional

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

Why does this statement work:

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

but not this one:

my_array.each { |value| puts value if !(value.to_f%2) }

Thanks in advance! Ogechi

1 Answer

This:

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

works, because it is looking for a specific value - 0.

0 is not a falsy value in Ruby:

http://codequizzes.wordpress.com/2013/09/29/truthy-and-falsey-in-ruby/

Although it is in some languages, such as JavaScript:

http://designpepper.com/blog/drips/truthy-and-falsy-values-in-javascript.html

So your expression:

my_array.each { |value| puts value if !(value.to_f%2) }

Always gets false in the if statement, because it always gets a truthy value (including 0) and makes the opposite using the ! sign, so it ALWAYS returns false. Hope this helps.

Hi Maciej, Thank you so much for shedding light on the problem! Much appreciated, :) Best, Ogechi