你要遍歷線,並查找與任-
或+
開始跟空格線:
text = %[
--- a/product.json
+++ b/product.json
@@ -1,4 +1,4 @@
{
- "name": "Coca Cola",
- "barcode": "41324134132"
+ "name": "Sprite",
+ "barcode": "41324134131"
}
\ No newline at end of file
]
text.lines.select{ |l| l.lstrip[/^[+-]\s/] }.map{ |s| s.split[1] }
# => ["\"name\":", "\"barcode\":", "\"name\":", "\"barcode\":"]
lines
在行尾分割一個字符串,返回整行,包括尾隨行尾字符。
lstrip
刪除行首的空白。這是規範化線,使正則表達式模式更簡單。
l.lstrip[/^[+-]\s/]
是一點點Ruby String,基本上說是將模式應用到字符串並返回匹配的文本。如果沒有匹配的字符串nil
將被返回,就select
而言,它將作爲虛假來使用。如果字符串的內容與模式匹配,則[]
將返回文本,該文本充當select
的真實值,然後傳遞該字符串。
map
遍歷select
傳遞給它的所有元素,並通過將元素拆分爲空格來轉換該元素,這是split
的默認行爲。 [1]
在字符串中返回第二個元素。
下面是同一個地方的備用路徑:
ary = []
text.lines.each do |l|
i = l.strip
ary << i if i[/^\{$/] .. i[/^}$/]
end
ary[1..-2].map{ |s| s.split[1] } # => ["\"name\":", "\"barcode\":", "\"name\":", "\"barcode\":"]
這將讓你開始。如何刪除重複項,去掉前導/尾隨雙引號和冒號是你的任務。
看起來你正在解析'diff'結果。你可以試試[unified_diff gem](https:// github。COM/rkneufeld/unified_diff)。免責聲明:我從來沒有使用那個寶石。 – zwippie
像'--- a/product.json'這樣的行的屬性名稱是什麼? – sawa
當您詢問代碼時,您需要顯示您嘗試的內容並解釋爲什麼它不適合您。有關如何正確提問的更多信息,請參見[help/on-topic],特別是#3。 –