[英]How can I split an array by 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 this: 我想得到这个:
[[1, [2, 3], 4], [5]]
The :open
effectively becomes [
and :close
becomes ]
:open
有效变为[
和:close
变为]
You could probably do this 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 should
clone
it before passing it in if you want to preserve it. 如果要保留它,则应在传入之前
clone
它。
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]]
The same to steenslag, but a little cleaner steenslag也一样,但有点清洁
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.