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]
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.
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.
The pop() method pops/removes the last element of an array, and returns it. This method changes the length of the array.
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.
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]
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