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']}
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.
p array.map { |x| x == 4 ? 'Z' : x } # => [1, 2, 3, 'Z']
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