Taking out a subpart from Enumerable
Posted
by sawa
on Stack Overflow
See other posts from Stack Overflow
or by sawa
Published on 2010-06-16T00:06:43Z
Indexed on
2010/06/16
0:12 UTC
Read the original article
Hit count: 222
I often want to take out a subpart from an Enumerable. The subpart is sometimes at the beginning and sometimes the end of the original Enumerable instance, and the length used to specify the subpart is sometimes that of the subpart and sometimes its complement. That gives four possibilities, but I only know how to do three of them. Is there a way to do the fourth one?
Getting the first n elements: [1, 2, 3, 4, 5].first(3) #=> [1, 2, 3] or [1, 2, 3, 4, 5].take(3) #=> [1, 2, 3]
Dropping the first n elements: [1, 2, 3, 4, 5].drop(3) #=> [4, 5]
Getting the last n elements: [1, 2, 3, 4, 5].last(3) #=> [3, 4, 5]
Dropping the last n elements: [1, 2, 3, 4, 5].some_method(3) #=> [1, 2]
© Stack Overflow or respective owner