tags:

views:

118

answers:

5

how can i substitue an element's 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]

A: 

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.

MikeSep
+2  A: 

Perhaps you mean:

a[5] = [11,22,33,44] # or a[-1] = ...
a.flatten!

A functional solution would be nicer, how about just:

a[0..-2] + [11, 22, 33, 44]

which yields...

=> [1, 2, 3, 4, 11, 22, 33, 44]
DigitalRoss
+2  A: 

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!

Benjamin Cox
A: 

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!
bta
+1  A: 

Not sure if you're looking to substitute a particular value or not, but this works:

$ irb
>> a = [1,2,3,4,5]
>> b = [11,22,33,44]
>> a.map! { |x| x == 5 ? b : x }.flatten!
>> a
=> [1, 2, 3, 4, 11, 22, 33, 44]
Ryan McGeary