【发布时间】:2011-01-21 15:50:34
【问题描述】:
想象一个这样的数组
[
"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 很陌生,所以我看起来真的很不雅,我在冒号上的行的拆分正则表达式上苦苦挣扎,所以第 3 行只在第一次出现时拆分。
谢谢!
编辑 这是我目前所拥有的
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
【问题讨论】:
-
要了解如何仅在第一次出现时使用
split(),请参阅我的答案,或者更确切地说是查看documentation forsplit并查看limit参数。 -
呸,谢谢,这个限制参数直到现在我才发现......