How can I split an array into delimiters in Ruby?

For example, if I have an array like this:

[:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]

      

I want to get the following:

[[1, [2, 3], 4], [5]]

      

The effect :open

becomes [

and :close

becomes]

+3
arrays ruby parsing


source to share


3 answers


You can probably do it with a stack, but it's pretty easy to design recursively:

#!/usr/bin/env ruby

x = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]

def parse(list)
  result = []
  while list.any?
    case (item = list.shift)
    when :open
      result.push(parse(list))
    when :close
      return result
    else
      result.push(item)
    end
  end

  return result
end

puts parse(x).inspect

      



Note that this will destroy your original array. You must have clone

it before transferring it if you want to keep it.

+10


source to share


ar = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
p eval(ar.inspect.gsub!(':open,', '[').gsub!(', :close', ']'))
#=> [[1, [2, 3], 4], [5]]

      



+4


source to share


The same with steenslag, but a little cleaner

a = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
eval(a.to_s.gsub(':open,','[').gsub(', :close',']'))
#=> [[1, [2, 3], 4], [5]]

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics