2015-05-22 55 views
0

我具有以下形式的数据:字符串转换为阵列的散列以指定的格式红宝石

Manju She is a good girl 
Raja He is okay boy 
Manju She comes late in the class 
Raja He is punctual 

我想创建从该这样的结构:

manju_hash = {"Manju1" => ["She", "is", "a","good","girl"], "Manju2" => ["She", "comes","late", "in", "the","class"]} 
raja_hash = {"Raja1" => ["He", "is", "okay", "boy"], "Raja2" => ["He", "is", "punctual"]} 

这是代码我写的:

manju_hash = Hash.new 
raja_hash = Hash.new 
data_lines.split(/\n+/).each do |val| 
    value =val.split(/\s+/) 
    key = value[0] 
    if (key=='Manju') 
     value.delete(key)  
     manju_hash.merge!(key+(manju_hash.size+1).to_s => value) 
    elsif (key=='Raja') 
     value.delete(key)  
     raja_hash.merge!(key+(raja_hash.size+1).to_s => value) 
    end 
end 

这是实现这一目标的正确方法,还是有一些其他惯用的ruby方式?其他一些改进,我可以做

回答

1

我只是做了一些重构,该算法是一样的,你.......

data = "Manju She is a good girl\nRaja He is okay boy\nManju She comes late in the class\nRaja He is punctual" 

hash = data.split("\n").map {|e| e.split(" ")}.group_by {|e| e[0] } 
#{"Manju"=>[["Manju", "She", "is", "a", "good", "girl"], ["Manju", "She", "comes", "late", "in", "the", "class"]], "Raja"=>[["Raja", "He", "is", "okay", "boy"], ["Raja", "He", "is", "punctual"]]} 

def function(data) 
    hash = Hash.new 
    data.each_with_index {|e, i| hash.merge!((e[0]+(i+1).to_s) => e[1..-1])} 
    hash 
end 



function(hash["Manju"]) 
    => {"Manju1"=>["She", "is", "a", "good", "girl"], "Manju2"=>["She", "comes", "late", "in", "the", "class"]} 

function(hash["Raja"]) 
=> {"Raja1"=>["He", "is", "okay", "boy"], "Raja2"=>["He", "is", "punctual"]} 
1

这是一个有点少重复,并且没有的if/else-的thingie

hash = {} 
counter = {} 
data_lines.split(/\n+/).each do |line| 
    key, value = line.split(' ', 2) 
    counter[key] = counter[key].to_i + 1 
    hash[key] = {} unless hash.has_key?(key) 
    hash[key][key + counter[key].to_s] = value.split(' ') 
end 

manju_hash = hash['Manju'] 
raja_hash = hash['Raja'] 

的演练,以使其更清晰(因为我不想添加注释在代码),基本上它是:

  • 分裂文本块进行
  • 分割空间上的每一行,但是它从值限制到单独的密钥
  • 保持计数一个密钥已被用来正确附加的次数
  • 添加顶级密钥如果这是第一次,例如,Raja
  • 将您的单词数组添加到附加了密钥的密钥计数器号
+0

'计数器[关键] .to_i'对我来说是一个谜,但。它如何转换?例如, – inquisitive

+0

计数器是一个包含所有名称和其出现次数的散列,例如{'Raja'=> 1,'Manju'=> 2}。 .to_i将从零转换为0 –