Conditional inserts in inject

  • Thread starter David Heinemeier Hansson
  • Start date
D

David Heinemeier Hansson

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
 
T

ts

D> %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
 
D

Dan Doel

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top