使用split分配字符串中的散列键和值

时间:2016-02-19 15:13:11

标签: ruby string split

我从文件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会返回""

4 个答案:

答案 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"}