First Even

Here’s an interesting problem in Ruby: return the first even number of an array in a Ruby manner.

This is what I came up with:

first_even = [1, 2, 5, 3, 4, 98].inject(1) do |m,x|
 (x % 2 == 0 && m % 2 != 0) ? x : m
end

puts first_even

What do you think?

By Albert on March 3, 2011 11:22 PM

Categories: