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]


沒有留言:

張貼留言

[ FP with Java ] Ch1 - What is functional programming

Preface   This chapter covers: ( Functional Programming in Java )  *  The benefits of functional programming *  Problems with side ef...