[
"A definition 1: this is the definition text",
"A definition 2: this is some other definition text",
"B definition 3: this could be: the definition text"
]
數組我想用下面的哈希
hash = {
:A => ["A definition 1", "this is the definition text", "A definition 2", "this is some other definition text"],
:B => ["B definition 3", "this could be: the definition text"]
}
我創建一個詞彙表來結束,用字母表中每個字母與定義數組的散列。
我對Ruby很新,所以我看起來真的很不雅,而且我在結腸線上的分割正則表達式上掙扎,因此第三行只在第一次出現時才分裂。
謝謝!
編輯 這裏是我到目前爲止
def self.build(lines)
alphabet = Hash.new()
lines.each do |line|
strings = line.split(/:/)
letter = strings[0][0,1].upcase
alphabet[letter] = Array.new if alphabet[letter].nil?
alphabet[letter] << strings[0]
alphabet[letter] << strings[1..(strings.size-1)].join.strip
end
alphabet
end
更換
Hash[ xxx ]
要了解如何使用'分裂()'只在第一次出現時,看到我的答案,或者說請參閱[文檔'split'](http://ruby-doc.org/core/classes/String.html#M001165)並查看'limit'參數。 – Phrogz銖謝謝,那限制param已經躲過我,直到現在... –