Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify only first n elements and return the modified array in ruby

Tags:

arrays

ruby

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.

like image 929
user3576036 Avatar asked Sep 05 '25 16:09

user3576036


1 Answers

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] 
like image 103
Cary Swoveland Avatar answered Sep 07 '25 18:09

Cary Swoveland