[英]Ruby how to iterate a collection and create a hash key if none exists, or add to the value if key does exist
我发现自己经常使用这种模式,我想知道内置库中是否有某些东西可以在不添加所有这些控制流语句的情况下执行此操作。 我所拥有的是:
input = <<TEXT
/us/programming/sports:model.channel.tnt.name
/us/programming/sports:model.channel.spice.name
/us/programming/sports:model.classificationwebgenre.us-entertainment.programming_link_text
/international-sports/package:model.language.international-sports.name
/brazilian/programming/sports:model.package.hbo-extra.description
TEXT
def self.create_hash(text)
output = {}
text.each_line("\n") do |line|
split_lines = line.split(":")
if output.has_key?(split_lines.first)
output[split_lines.first] << split_lines[1][0..-2]
else
output[split_lines.first] = [split_lines[1][0..-2]]
end
end
output
end
结束
也是这样的输出:
{
"/us/programming/sports" => ["model.channel.tnt.name", "model.channel.spice.name", "model.classificationwebgenre.us-entertainment.programming_link_text"],
"/international-sports/package" => ["model.language.international-sports.name"],
"/brazilian/programming/sports" => ["model.package.hbo-extra.description"]
}
我是不是只是用编写它们的方式使事情变得过于复杂? 有没有惯用的方法用红宝石来写这个? 提前致谢。
不确定是否更快,但是更干净
def self.create_hash(text)
output = {}
text.each_line("\n") do |line|
split_lines = line.split(":")
output[split_lines.first] ||= []
output[split_lines.first] << split_lines[1][0..-2]
end
output
end
只需使用默认值定义output
:
output = Hash.new { |k, v| k[v] = [] }
那将使您的代码变成:
def self.create_hash(text)
output = Hash.new { |k, v| k[v] = [] }
text.each_line("\n") do |line|
split_lines = line.split(":")
output[split_lines.first] << split_lines[1][0..-2]
end
output
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.