Replace one element in an array

I have an array with unique elements. Is there a way to replace a specific 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']} 
+8
source share
4 answers
 p array.map { |x| x == 4 ? 'Z' : x } # => [1, 2, 3, 'Z'] 
+16
source

You can do it like:

 array[array.index(4)] = "Z" 

If the element is not necessarily in the array, then

 if i = array.index(4) array[i] = "Z" end 
+10
source

You can use Array # map

 array = array.map do |e| if e == 4 'Z' else e end end 

to edit the array in place, rather than create a new array, use Array # map!

If you have more than one thing that you want to replace, you can use the hash to map the old to the new:

 replacements = { 4 => 'Z', 5 => 'five', } array = array.map do |e| replacements.fetch(e, e) end 

This makes use of the Hash # fetch function, where if the key is not found, the second argument is used by default.

+5
source

A very simple solution, assuming there will be no duplicates, and the order does not matter:

 hash = { 'One' => [1, 2, 3, 4] } hash['One'].instance_eval { push 'Z' if delete 4 } 

instance_eval sets the value of self to the receiver (in this case, it is an array [1,2,3,4] ) for the time the block is transferred to it.

+4
source

Source: https://habr.com/ru/post/976850/


All Articles