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 常見問題 ] python generator “send” function purpose?

Source From  Here   Question   Can someone give me an example of why the "send" function associated with Python generator function...