Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace an array's element?

Tags:

arrays

ruby

How can I substitue an element in an array?

a = [1,2,3,4,5] 

I need to replace 5 with [11,22,33,44].flatten!

so that a now becomes

a = [1,2,3,4,11,22,33,44] 
like image 795
gweg Avatar asked Nov 09 '09 23:11

gweg


People also ask

How do you replace values in an array of objects?

To change the value of an object in an array:Use the Array. map() method to iterate over the array. Check if each object is the one to be updated. Use the spread syntax to update the value of the matching object.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How will change the last element of an array?

The pop() method pops/removes the last element of an array, and returns it. This method changes the length of the array.


2 Answers

Not sure if you're looking to substitute a particular value or not, but this works:

a = [1, 2, 3, 4, 5] b = [11, 22, 33, 44] a.map! { |x| x == 5 ? b : x }.flatten! 

This iterates over the values of a, and when it finds a value of 5, it replaces that value with array b, then flattens the arrays into one array.

like image 190
Ryan McGeary Avatar answered Oct 02 '22 18:10

Ryan McGeary


Perhaps you mean:

a[4] = [11,22,33,44] # or a[-1] = ... a.flatten! 

A functional solution might be nicer, how about just:

a[0..-2] + [11, 22, 33, 44] 

which yields...

=> [1, 2, 3, 4, 11, 22, 33, 44] 
like image 20
DigitalRoss Avatar answered Oct 02 '22 20:10

DigitalRoss