Conditional inserts in inject

Consider:

%w{ one two three }.inject(Array.new) { |a, e| a << e if e != “three” }

I would have expected that to return:

[ “one”, “two” ]

Instead it returns nil.

What am I missing? Or isn’t it possible to use conditions in an inject
expression? If not, how would one go about archiving the same?

/ David

%w{ one two three }.inject(Array.new) { |a, e| a << e if e != "three" }

                                                  ^^^^^^^^^^^^^^^^^^^^^^

this is the same than

   if e != "three"
      a << e
   else
      nil
   end

this is why it return nil

Guy Decoux

%w{ one two three }.inject(Array.new) { |a, e| if e != “three” then a <<
e else a end }

The value of the block is assigned to a in the next iteration, or
returned if it’s the last
iteration, so you need to return the array itself if you’re doing nothing.

David Heinemeier Hansson wrote:

···

Consider:

%w{ one two three }.inject(Array.new) { |a, e| a << e if e != “three” }

I would have expected that to return:

[ “one”, “two” ]

Instead it returns nil.

What am I missing? Or isn’t it possible to use conditions in an inject
expression? If not, how would one go about archiving the same?