Create array of n items based on integer value

后端 未结 5 611
小鲜肉
小鲜肉 2020-12-13 11:58

Given I have an integer value of, e.g., 10.

How can I create an array of 10 elements like [1,2,3,4,5,6,7,8,9,10]?

5条回答
  •  天命终不由人
    2020-12-13 12:32

    You can just splat a range:

    [*1..10]
    #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    Ruby 1.9 allows multiple splats, which is rather handy:

    [*1..3, *?a..?c]
    #=> [1, 2, 3, "a", "b", "c"]
    

提交回复
热议问题