Brand
Brand

Reputation: 1701

Iterate array using range

This is what I want to do

a = [1, 2, 3, 4]
a[1] = 0
a[2] = 0

one way to do this is to loop

(1..2).each { |x| x = 0 }

is there a way to do this somehow with ranges or splats? something like

a[(1..2)] = 0

Upvotes: 4

Views: 1949

Answers (3)

chrisun
chrisun

Reputation: 236

Or, with Array#fill

a.fill(0, 1..2)

Upvotes: 2

derp
derp

Reputation: 3030

With range

ary = [1, 2, 3, 4]
ary[1..2] = [0,0]

Using [start, length]

a = [1,2,3,4]
a[1,2] = [0,0]

Upvotes: 1

taiansu
taiansu

Reputation: 2775

a = [1, 2, 3, 4]
a[1..2] = [0] * 2
p a #[1, 0, 0, 4]

You can't just type a[1..2] = 0 at line 2, cause the array a will become [1, 0, 4]

Upvotes: 5

Related Questions