我从文件birthdays.txt
中检索了一些字符串。字符串的示例如下:
Christopher Alexander, Oct 4, 1936
我想分隔字符串,让变量name
成为散列键,birthdate
为散列值。这是我的代码:
birthdays = {}
File.read('birthdays.txt').each_line do |line|
line = line.chomp
name, birthdate = line.split(/\s*,\s*/).first
birthdays = {"#{name}" => "#{birthdate}"}
puts birthdays
end
我设法将name
分配给密钥。但是,birthdate
会返回""
。
答案 0 :(得分:1)
File.new('birthdays.txt').each.with_object({}) do
|line, birthdays|
birthdays.store(*line.chomp.split(/\s*,\s*/, 2))
puts birthdays
end
答案 1 :(得分:1)
我觉得其他一些解决方案正在过度思考这一点。您需要做的就是将每一行分成两部分,即第一个逗号之前的部分和之后的部分,您可以使用line.split(/,\s*/, 2)
执行,然后在生成的数组数组上调用to_h
:< / p>
data = <<END
Christopher Alexander, Oct 4, 1936
Winston Churchill, Nov 30, 1874
Max Headroom, Apr 4, 1985
END
data.each_line.map do |line|
line.chomp.split(/,\s*/, 2)
end.to_h
# => { "Christopher Alexander" => "Oct 4, 1936",
# "Winston Churchill" => "Nov 30, 1874",
# "Max Headroom" => "April 4, 1985" }
(当然,您希望将data
替换为您的File对象。)
答案 2 :(得分:0)
birthdays = Hash.new
File.read('birthdays.txt').each_line do |line|
line = line.chomp
name, birthdate = line.split(/\s*,\s*/, 2)
birthdays[name]= birthdate
puts birthdays
end
答案 3 :(得分:0)
使用@Jordan的data
:
data.each_line.with_object({}) do |line, h|
name, _, bdate = line.chomp.partition(/,\s*/)
h[name] = bdate
end
#=> {"Christopher Alexander"=>"Oct 4, 1936",
# "Winston Churchill"=>"Nov 30, 1874",
# "Max Headroom"=>"Apr 4, 1985"}