Returning first x items from array

后端 未结 5 652
小蘑菇
小蘑菇 2020-12-01 03:14

I want to return first 5 items from array. How can I do this?

5条回答
  •  忘掉有多难
    2020-12-01 03:39

    A more object oriented way would be to provide a range to the #[] method. For instance:

    Say you want the first 3 items from an array.

    numbers = [1,2,3,4,5,6]

    numbers[0..2] # => [1,2,3]

    Say you want the first x items from an array.

    numbers[0..x-1]

    The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.

    numbers[0..100] # => [1,2,3,4,5,6]

提交回复
热议问题