[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Conditional inserts in inject

David Heinemeier Hansson

9/8/2003 4:23:00 PM

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


2 Answers

ts

9/8/2003 4:30:00 PM

0

>>>>> "D" == David Heinemeier Hansson <david@loudthinking.com> writes:

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



Dan Doel

9/8/2003 7:30:00 PM

0

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