Reputation: 13
I am using Ruby, and I am relearning arrays and trying to better understand them. I know what they are but have never fully utilized them. I have an array, odds, and wanted to double every number in it. I came up with the below solution; however, I wanted to see if there was a more elegant/simple solution to my problem.
odds = [1,3,5,7,9]
odds.each do |x|
odds[odds.index(x)]=x*2
end
end result is odds = [2,6,10,14,18]
Upvotes: 0
Views: 90
Reputation: 5637
If you really want to modify in place, and you really want to use each
, I guess your approach is as good as any. It doesn't feel idiomatic, but it does meet your stated constraints.
Here are some more common approaches:
Array.map
Mapping the array with map
won't modify the original array (it's not in-place), which is often a good thing, but it might not be what you're looking for:
odds.map { |x| x*2 }
Array.map!
If you really do want to modify the original array, you can use map!
to map in-place:
odds.map! { |x| x*2 }
Array.each_index
You did ask specifically about each
, so if you want to use an each
and you want to modify the original array, each_index
might be your best bet:
odds.each_index { |i| odds[i] *= 2 }
Upvotes: 1
Reputation: 6098
You can use the map!
enumerator to modify every item in an array:
odds.map!{ |x| x*2}
Upvotes: 3