Siddharth Singh
Siddharth Singh

Reputation: 19

How to modify subarray in place

I have:

a = [1,2,4,5]

I want to modify this array to get:

a #=> [1,0,0,0]

This can be done with an each loop, but I'm trying not to use a loop here. Here's my code:

a.values_at(1..3).map! {|i| i = 0}

Upvotes: 0

Views: 81

Answers (1)

Stefan
Stefan

Reputation: 114248

You can use fill:

a = [1, 2, 4, 5]
#=> [1, 2, 4, 5]

a.fill(0, 1)
#=> [1, 0, 0, 0]

a
#=> [1, 0, 0, 0]

The above code sets the elements in a to 0, starting at index 1.

Upvotes: 7

Related Questions