我有一个任意字符串的可变长度数组。一个一致性是字符串“你好”重复,我想分组的字符串“你好”。按重复值拆分数组
所以给出这样的:
[
"hello\r\n",
"I\r\n",
"am\r\n",
"Bob\r\n",
"hello\r\n",
"How\r\n",
"are you?\r\n"
]
我想这一点:
[
[
"hello\r\n",
"I\r\n",
"am\r\n",
"Bob\r\n"
],
[
"hello\r\n",
"How\r\n",
"are you?\r\n"
]
]
我曾尝试:
partition = []
last = input.size
index = 0
input.each_with_object([]) do |line, acc|
index += 1
if line == "hello\r\n"
acc << partition
partition = []
partition << line
else
partition << line
end
if index == last
acc << partition
end
acc
end.delete_if(&:blank?)
=> [["hello\r\n", "I\r\n", "am\r\n", "Bob\r\n"], ["hello\r\n", "How\r\n", "are you?\r\n"]]
结果是正确的,但有可能做什么我想用ruby数组迭代器?我的解决方案似乎笨重。
什么是想要的返回值,如果在字符串'[ “咳咳\ r \ n”, “你好\ r \ n”, “我用\ r \ n”, “AM \ r \ n” ,“Bob \ r \ n”,“chellos \ r \ n”,“你好吗?\ r \ n”]?当你举一个例子时,给每个输入分配一个变量是很有帮助的(例如,'arr = [“hello \ r \ n”,...]')这使得读者可以在回答和评论中引用变量而无需定义它们。 –