Skip to content
Tags

,

Array#take_while

July 9, 2013

Array#map necessarily works on all elements.

If you only want to pick certain elements from an array use Array#take_while

a = [1, 2, 3, 4, 5, 0]
a.take_while { |i| i < 3 }  
#=> [1, 2]

However, it seems that it doesn’t always work. Should be a bug:

2.0.0-p247 :098 > a.class
=> Array
2.0.0-p247 :099 > a[62].class
=> String
2.0.0-p247 :100 > a[62]
=> "1-7"
2.0.0-p247 :096 > a[62].scan(/\D/)
=> ["-"]
2.0.0-p247 :097 > a[62].scan(/\D/).any?
=> true
2.0.0-p247 :101 > a.take_while{|h| h.scan(/\D/).any? } 
=> []

 NOTE: A good alternative for Array#take_while might be Array#keep_if
Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: