Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a single element in an array

Tags:

I have an array with unique elements. Is there a way to replace a certain value in it with another value without using its index value?

Examples:

array = [1,2,3,4] if array.include? 4 #  "replace 4 with 'Z'" end array #=> [1,2,3,'Z']  hash = {"One" => [1,2,3,4]} if hash["One"].include? 4 #  "replace 4 with 'Z'" end hash #=> {"One" => [1,2,3,'Z']} 
like image 860
Lasonic Avatar asked Oct 16 '14 23:10

Lasonic


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.


1 Answers

p array.map { |x| x == 4 ? 'Z' : x }  # => [1, 2, 3, 'Z'] 
like image 66
Johnson Avatar answered Sep 23 '22 03:09

Johnson