Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between #take_while and #select

Tags:

ruby

What is the difference between #take_while and #select

Don't both methods do the same thing?

p [1,2,3,4].take_while { |e| e < 3 } # prints [1,2]
p [1,2,3,4].select     { |e| e < 3 } # prints [1,2]
like image 386
the_prole Avatar asked Nov 07 '25 17:11

the_prole


1 Answers

There is a difference, take_while stops from the moment the evaluation in the block is false, select will continue and evaluate everything.

[1,2,3,4,1].take_while{ |e| e < 3 } # prints [1,2]
[1,2,3,4,1].select{ |e| e < 3 } # prints [1,2,1]
like image 100
peter Avatar answered Nov 11 '25 23:11

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!