Understanding Ruby Enumerable#map (with more complex blocks)

Posted by mstksg on Stack Overflow See other posts from Stack Overflow or by mstksg
Published on 2010-06-15T01:25:37Z Indexed on 2010/06/15 1:32 UTC
Read the original article Hit count: 279

Let's say I have a function

def odd_or_even n
  if n%2 == 0
    return :even
  else
    return :odd
  end
end

And I had a simple enumerable array

simple = [1,2,3,4,5]

And I ran it through map, with my function, using a do-end block:

simple.map do
  |n| odd_or_even(n)
end
# => [:odd,:even,:odd,:even,:odd]

How could I do this without, say, defining the function in the first place? For example,

# does not work
simple.map do |n|
  if n%2 == 0
    return :even
  else
    return :odd
  end
end

# Desired result:
# => [:odd,:even,:odd,:even,:odd]

is not valid ruby, and the compiler gets mad at me for even thinking about it. But how would I implement an equivalent sort of thing, that works?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about language-features