LuminaChen
LuminaChen

Reputation: 135

How to insert elements into an array

I have an array consisting of unknown elements:

myary = [100, "hello", 20, 40, "hi"]

I want to put integer 10 after each element to make it into this:

myary = [100, 10, "hello", 10, 20, 10, 40, 10, "hi", 10]

Is there a way or a method to do it?

Another problem is that I need to add integer 10 before a string "hello".

myary = [100, 10,"hello", 20, 40, "hi"]

Upvotes: 2

Views: 819

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Is this what you want ?

myary = [100, "hello", 20, 40, "hi"]
myary.flat_map { |i| [i, 10] }
# => [100, 10, "hello", 10, 20, 10, 40, 10, "hi", 10] 
myary.flat_map { |i| i == 'hello' ? [10, i] : i }
# => [100, 10,"hello", 20, 40, "hi"]

Read #flat_map method.

Upvotes: 9

Related Questions