我有一個任意字符串的可變長度數組。一個一致性是字符串「你好」重複,我想分組的字符串「你好」。按重複值拆分數組
所以給出這樣的:
[
"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」,...]')這使得讀者可以在回答和評論中引用變量而無需定義它們。 –