程式扎記: [ 常見問題 ] Correct way to populate an Array with a Range in Ruby

標籤

2014年11月5日 星期三

[ 常見問題 ] Correct way to populate an Array with a Range in Ruby

Source From Here
Question
Is there a gracefully way to obtain Array with a number range like:
>> a = []
=> []
>> for i in (1..10)
>> a << i
>> end
=> 1..10
>> a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How-To
You can create an array with a Range using splat,
>> a=*(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

using the Array constructor,
>> a = Array(1..10)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

or using to_a
>> a=(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!