Lasonic
Lasonic

Reputation: 901

Replace a single element in an array

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']}

Upvotes: 27

Views: 63888

Answers (4)

Matheus Moreira
Matheus Moreira

Reputation: 17030

A very simple solution that assumes there will be no duplicates and that the order doesn't 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, the array [1,2,3,4]) for the duration of the block passed to it.

Upvotes: 2

Johnson
Johnson

Reputation: 1749

p array.map { |x| x == 4 ? 'Z' : x }

# => [1, 2, 3, 'Z']

Upvotes: 42

sawa
sawa

Reputation: 168269

You can do it as:

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

If the element is not necessarily in the array, then

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

Upvotes: 20

Wayne Conrad
Wayne Conrad

Reputation: 108269

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 creating a new array, use Array#map!

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

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

This make uses of a feature of Hash#fetch, where if the key is not found, the second argument is used as a default.

Upvotes: 11

Related Questions