4

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
0

3 Answers 3

5
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]

Sign up to request clarification or add additional context in comments.

1 Comment

a[1..2] = 0, 0, a[1,2] = 0,0, a[1..2] = *[0,0]
2

Or, with Array#fill

a.fill(0, 1..2)

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.