Ruby Tuesday – Enumerable#drop_while

Today’s Ruby Tuesday entry is on Enumerable#drop_while.

Enumerable#drop_while drops items from the beginning of the enum up to, but not including, the first element for which the block returns a non-truthy value.

[1, 2, 3, 4, 5, 6].drop_while {|item| item < 5}
# => [5, 6]
["a", "foo", "snafu"].drop_while {|item| item.length < 3}
=> ["foo", "snafu"]
[1, 4, 2, 5, 3, 6].drop_while {|item| true}
# => []
[1, 4, 2, 5, 3, 6].drop_while {|item| false}
# => [1, 4, 2, 5, 3, 6]
[].drop_while{|item| true }
# => []
[].drop_while{|item| false }
# => []

Evaluation stops, and does not check the rest of the list if a falsey value is returned. This will leave other values in the list that might return a falsey value, unlike Enumerable#reject which removes all items from the enum.

[1, 4, 2, 5, 3, 6].drop_while {|item| item < 5}
# => [5, 3, 6]

Enumerable#drop_while can also leave values in your enum that would normally cause the block to error out, because the evaluation against the list stops after the first falsey value is encountered.

["a", "foo", "snafu", "b", :c].drop_while {|item| item.length < 3}
# => ["foo", "snafu", "b", :c]

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *