我有一系列字符,如下所示:
chars = ["x", "o", "o", "x", "x", "o", "o", "x", "x", "x", "o", "o"]
我需要获取连续字符的数量和该字符串的索引。它应该是这样的:
[
{ index: 0, length: 1 }, # "x"
{ index: 1, length: 2 }, # "o", "o"
{ index: 3, length: 2 }, # "x", "x"
{ index: 5, length: 2 }, # "o", "o"
{ index: 7, length: 3 }, # "x", "x", "x"
{ index: 10, length: 2 } # "o", "o"
]
有没有简单的方法来实现这一目标?
答案 0 :(得分:4)
不确定你是否称之为一种简单的方式,但这是一种单行的方式。结果数组的格式为[index, length]
。
chars.each_with_index.chunk {|i, _| i}.map {|_, y| [y.first.last, y.length]}
#=> [[0, 1], [1, 2], [3, 2], [5, 2], [7, 3], [10, 2]]
答案 1 :(得分:1)
另外两种方法:
使用Emumerable#slice_when(v.2.2 +)
count = 0
arr = chars.slice_when { |a,b| a != b }.map do |arr|
sz = arr.size
h = { index: count, length: sz }
count += sz
h
end
#=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2},
# {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}]
使用带反向引用的正则表达式
count = 0
arr = chars.join.scan(/((.)\2*)/).map do |run, _|
sz = run.size
h = { index: count, length: sz }
count += sz
h
end
#=> [{:index=>0, :length=>1}, {:index=>1, :length=>2}, {:index=>3, :length=>2},
# {:index=>5, :length=>2}, {:index=>7, :length=>3}, {:index=>10, :length=>2}]