Creating an array with incrementing values up to a certain number

B

Brian Ross

[Note: parts of this message were removed to make it a legal post.]

Hello,

Another basic question, thanks for the help on the last one. I wanted to
come up with the above described program and came up with this:

# array.rb start

a = [1]
x = 0
while x < 99
a[(x+1)] = (a[x] + 1)
x = x + 1
end
p a

# array.rb end

This worked fine, but is there a more elegant way of doing this? It seems a
bit clumsy.

Brian
 
F

Farrel Lifson

irb(main):004:0> i = 0
=> 0
irb(main):005:0> a = Array.new(99){i+=1}
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Farrel
 
R

Rick DeNatale

[Note: parts of this message were removed to make it a legal post.]

Hello,

Another basic question, thanks for the help on the last one. I wanted to
come up with the above described program and came up with this:

# array.rb start

a = [1]
x = 0
while x < 99
a[(x+1)] = (a[x] + 1)
x = x + 1
end
p a

# array.rb end

This worked fine, but is there a more elegant way of doing this? It seems a
bit clumsy.
p (1..100).to_a
 
D

David A. Black

Hi --

Hello,

Another basic question, thanks for the help on the last one. I wanted to
come up with the above described program and came up with this:

# array.rb start

a = [1]
x = 0
while x < 99
a[(x+1)] = (a[x] + 1)
x = x + 1
end
p a

# array.rb end

This worked fine, but is there a more elegant way of doing this? It seems a
bit clumsy.

In addition to the other answers:

a = [*1..99]


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top