2011-01-21 13 views
1

想像這樣最乾淨的Ruby代碼分裂特定規則的字符串

[ 
"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 
+1

更換Hash[ xxx ]要了解如何使用'分裂()'只在第一次出現時,看到我的答案,或者說請參閱[文檔'split'](http://ruby-doc.org/core/classes/String.html#M001165)並查看'limit'參數。 – Phrogz

+0

銖謝謝,那限制param已經躲過我,直到現在... –

回答

4

提供raw_definitions是您的輸入:

sorted_defs = Hash.new{|hash, key| hash[key] = Array.new;} 

raw_definitions.each do |d| 
    d.match(/^([a-zA-Z])(.*?):(.*)$/) 
    sorted_defs[$1.upcase]<<$1+$2 
    sorted_defs[$1.upcase]<<$3.strip 
end 
+0

好幾乎工作,$ 2缺少$ 1,你能否再次開始第二場比賽開始? –

+0

是的,這就是爲什麼我加了$ 1 + $ 2試試。此修訂產生正確的輸出,在IRB中進行測試。 –

2

只是爲了好玩,這裏是一個純粹的功能替代:

defs = [ 
    "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 = Hash[ 
    defs.group_by{ |s| s[0].to_sym }.map do |sym,strs| 
    [ sym, strs.map{ |s| s[2..-1].split(/\s*:\s*/,2) }.flatten ] 
    end 
] 

require 'pp' 
pp hash 
#=> {:A=> 
#=> ["definition 1", 
#=> "this is the definition text", 
#=> "definition 2", 
#=> "this is some other definition text"], 
#=> :B=>["definition 3", "this could be: the definition text"]} 

而且不是純粹的福具有相同的結果nctional變化:

hash = defs.group_by{ |s| s[0].to_sym }.tap do |h| 
    h.each do |sym,strs| 
    h[sym] = strs.map{ |s| s[2..-1].split(/\s*:\s*/,2) }.flatten 
    end 
end 

請注意,這些解決方案只能在Ruby 1.9中,由於使用的s[0].to_sym工作;要在1.8.7中工作,您必須將其更改爲s[0,1].to_sym。要在1.8.6的第一個解決方案的工作,你會進一步有Hash[ *xxx.flatten ]

+0

打破了我的頭腦閱讀它,但+1顯示一個非常酷的方式 –

+0

這是一個有趣的解決方案,使用紅寶石語言的細微差別。感謝分享! –