I need to perform an operation on k
set of values of an array and return the modified array.
I have an array = [10,32,5,6,7]
Let us say k=2
I am trying to take only the first two elements here by doing:
arr2=[]
array[0..k-1].each do |i|
res=i.to_f/2.0
arr2.push(res.round)
end
=>arr2=[5,16]
I want to replace the first 2 elements in the array
with arr2
values.
How can I achieve this without having to create so many new arrays.
There is no need to iterate the entire array.
array = [10,32,5,6,7]
array[0, 2] = array[0, 2].map { |n| n/2.0 }
array
#=> [5.0, 16.0, 5, 6, 7]
or
2.times { |i| array[i] = array[i]/2.0 }
array
#=> [5.0, 16.0, 5, 6, 7]
The above reflects my understanding that the original array is to be mutated. If the array is not to be mutated one could write the following.
array[0, 2].map { |n| n/2.0 }.concat(array[2..-1])
#=> [5.0, 16.0, 5, 6, 7]
array
#=> [10, 32, 5, 6, 7]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With