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]


沒有留言:

張貼留言

[ Python 文章收集 ] List Comprehensions and Generator Expressions

Source From  Here   Preface   Do you know the difference between the following syntax?  view plain copy to clipboard print ? [x  for ...