Shona
Shona

Reputation: 91

How do i concatinate some element of array and recreate array in ruby

I have a string. I need to split it and assign values to hash. But before assigning it, I need to modify the original array and concatenate some of its elements then recreate the array again. Please help me on how to do it in ruby.

Consider

  array = ["unix", "2", "[", "ACC", "]", "STREAM", "LISTENING", "12459", "tmp/control"]. 

I need to concatenate "[", "ACC", "]".

Now the new Array should look like

  array = ["unix", "2", "[ ACC ]", "STREAM", "LISTENING", "12459", "tmp/control"].

Please suggest.

Upvotes: 1

Views: 53

Answers (2)

hirolau
hirolau

Reputation: 13921

Posting this answer as 1: The accepted solution only works with one set of square brackets and 2: How often do you actually get to solve something using flip flop?

array = ["unix", "2", "[", "ACC", "]", "STREAM", "[", "some",  "other", "]", "x"]

array = array.chunk{|x| (x=='['..x==']') ? true : false }
            .map{|join, array| join ? array.join(' ') : array}
            .flatten

p array #=> ["unix", "2", "[ ACC ]", "STREAM", "[ some other ]", "x"]

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118271

array = ["unix", "2", "[", "ACC", "]", "STREAM", "LISTENING", "12459", "tmp/control"]
m,n = array.index('['),array.index(']')
array[m..n]=array[m..n].join(" ")
p array 
# => ["unix", "2", "[ ACC ]", "STREAM", "LISTENING", "12459", "tmp/control"]

Upvotes: 1

Related Questions