FourScore
FourScore

Reputation: 171

How can I fill an array from 1 to x in ruby?

I currently have this code:

ans = Array.new(3)
      ans.length.times do |x|
        ans[x] = x + 1
      end

Is there any faster way to do this?

Upvotes: 0

Views: 60

Answers (4)

steenslag
steenslag

Reputation: 80065

Unsplat a range, like this:

ans = *1..3

Upvotes: 1

Grych
Grych

Reputation: 2901

Use range and convert it into an array:

(1..3).to_a

Upvotes: 2

Linuxios
Linuxios

Reputation: 35793

How about this:

ans = (1..3).to_a

This uses what Ruby calls a Range.

Depending on what you want to do with ans, you may want to use the range directly without converting it to an array.

Upvotes: 3

astreal
astreal

Reputation: 3513

The easiest way would be:

ans = (1..3).to_a

Upvotes: 2

Related Questions