Arrays 将字符串转换为指定格式的数组哈希
我有以下表格的数据:Arrays 将字符串转换为指定格式的数组哈希,arrays,ruby,input,hash,Arrays,Ruby,Input,Hash,我有以下表格的数据: 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"]
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方法?我可以做的其他一些改进这是重复性少一点,并且没有if/else的东西
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
- 将单词数组添加到附加有计数器编号的键中
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"]}
计数器[键]。对我来说,密码是个谜。它是如何转换的?计数器是一个包含所有名称和出现次数的散列,例如{'Raja'=>1,'Manju'=>2}。.to_i用于从nil转换为0