1

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.

2
  • I wonder how people create complexities Commented Nov 8, 2013 at 12:45
  • 1
    Show the original string, perhaps there is a better way to split it. Commented Nov 8, 2013 at 12:47

2 Answers 2

1
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"]
Sign up to request clarification or add additional context in comments.

4 Comments

Missing one , in case of ` array = ["unix", "2", "[", "ACC", "ACC2", "]", "STREAM", "LISTENING", "12459", "tmp/control"]` :)
@AmolPujari OP didn't mention that...In such a case this answer needs to be changed... :)
its would be interested to know and review code generating the input array here.
It is interesting to see an accepted answer with 4 comments and not a singl upvote. +1
1

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.