Reputation: 2882
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]
Upvotes: 27
Views: 50737
Reputation: 239914
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.
Upvotes: 45
Reputation:
Here is another simple way to replace the value 5
in the array:
a[-1, 1] = [11, 22, 33, 44]
This uses the Array#[]=
method. I'm not exactly sure why it works though.
Upvotes: 2
Reputation: 226
Array#delete will return the item or nil. You may use this to know whether or not to push your new values
a.push 11,22,33,44 if a.delete 5
Upvotes: 7
Reputation: 146043
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]
Upvotes: 19
Reputation: 705
The version of bta using a.index(5) is the fastest one:
a[a.index(5)] = b if a.index(5) # 5.133327 sec/10^6
At least 10% faster than Ryan McGeary's one:
a.map!{ |x| x == 5 ? b : x } # 5.647182 sec/10^6
However, note that a.index(5) only return the first index where 5 is found. So, given an array where 5 appears more than once, results will be different:
a = [1, 2, 3, 4, 5, 5]
b = [11,22,33,44]
a[a.index(5)] = b if a.index(5)
a.flatten # => [1, 2, 3, 4, 11, 22, 33, 44, 5]
a.map!{ |x| x == 5 ? b : x }
a.flatten # => [1, 2, 3, 4, 11, 22, 33, 44, 11, 22, 33, 44]
Upvotes: 14
Reputation: 45057
This variant will find the 5
no matter where in the array it is.
a = [1, 2, 3, 4, 5]
a[a.index(5)]=[11, 22, 33, 44] if a.index(5)
a.flatten!
Upvotes: 5
Reputation: 6120
You really don't have to flatten if you just concatenate. So trim the last element off the first array and concatenate them:
a = [ 1, 2, 3, 4, 5 ] #=> [1, 2, 3, 4, 5]
t = [11, 22, 33, 44] #=> [11, 22, 33, 44]
result = a[0..-2] + t #=> [1, 2, 3, 4, 11, 22, 33, 44]
a[0..-2] is a slice operation that takes all but the last element of the array.
Hope it helps!
Upvotes: 5
Reputation: 10375
gweg, not sure what you're trying to do here, but are you looking for something like this?
a = [1, 2, 3, 4, 5]
a.delete_at(4)
a = a.concat([11,22,33,44])
There are a number of ways of doing this -- I don't think the code above is especially nice looking. It all depends on the significance of '5' in your original array.
Upvotes: 0