delta
delta

Reputation: 3818

How to change the element part of an array while iterating

An array xs consists of numbers from 0 to 9:

xs = [*0..9]

Test parity, and store result in place:

xs.map!(&:odd?)
puts xs.join(" ") 
# => false, true, ..., true

xs changed as expected. But I just want to change a part of the array

xs[5..-1].map!(&:odd?)
puts xs.join(" ")
# => 0 1 2 3 4 5 6 7 8 9

I guess the slice operation returns a copy. Or some other reasons.

xs[...] = xs[...].some_operation is a solution, but is there any way to do this without assignment?

Upvotes: 1

Views: 79

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

Here is a way to do this:

xs.fill(5..-1) { |i| xs[i].odd? }
#=> 0 1 2 3 4 true false true false true

Upvotes: 8

Related Questions