我正在研究Chris Pine的Learn to Program一书中的一个示例问题,我在删除哈希值中的空格时遇到了问题。
我从一个包含姓名和生日信息的txt文件开始,如下所示:
Christopher Alexander, Oct 4, 1936
Christopher Lambert, Mar 29, 1957
Christopher Lee, May 27, 1922
Christopher Lloyd, Oct 22, 1938
Christopher Pine, Aug 3, 1976
然后我遍历每一行,在第一个逗号分割,然后尝试遍历每个键,值以去除空白区域。
birth_dates = Hash.new {}
File.open 'birthdays.txt', 'r' do |f|
f.read.each_line do |line|
name, date = line.split(/,/, 2)
birth_dates[name] = date
birth_dates.each_key { |a| birth_dates[a].strip! }
end
但没有任何事情被剥夺。
{"Christopher Alexander"=>" Oct 4, 1936", "Christopher Lambert"=>" Mar 29, 1957", "Christopher Lee"=>" May 27, 1922", "Christopher Lloyd"=>" Oct 22, 1938", "Christopher Pine"=>" Aug 3, 1976", "Christopher Plummer"=>" Dec 13, 1927", "Christopher Walken"=>" Mar 31, 1943", "The King of Spain"=>" Jan 5, 1938"}
我已经看到了一些使用.map的数组解决方案 - 但这是我遇到的唯一哈希示例。知道为什么它可能不适合我吗?
更新:根据sawa的评论删除多余的chomp。
答案 0 :(得分:2)
对于解析逗号分隔文件,我使用像这样的
def parse_birthdays(file='birthdays.txt', hash={})
CSV.foreach(file, :converters=> lambda {|f| f ? f.strip : nil}){|name, date, year|hash[name] = "#{year}-#{date.gsub(/ +/,'-')}" }
hash
end
parse_birthdays
# {"Christopher Alexander"=>"1936-Oct-4", "Christopher Lambert"=>"1957-Mar-29", "Christopher Lee"=>"1922-May-27", "Christopher Lloyd"=>"1938-Oct-22", "Christopher Pine"=>"1976-Aug-3"}
如果您需要真实日期,可以放弃lambda
def parse_birthdays(file='birthdays.txt', hash={})
CSV.foreach(file){|name, date, year|hash[name] = Date.parse("#{year}-#{date}")}
hash
end
parse_birthdays
# {"Christopher Alexander"=>#<Date: 2014-10-04 ((2456935j,0s,0n),+0s,2299161j)>, "Christopher Lambert"=>#<Date: 2014-03-29 ((2456746j,0s,0n),+0s,2299161j)>, "Christopher Lee"=>#<Date: 2014-05-27 ((2456805j,0s,0n),+0s,2299161j)>, "Christopher Lloyd"=>#<Date: 2014-10-22 ((2456953j,0s,0n),+0s,2299161j)>, "Christopher Pine"=>#<Date: 2014-08-03 ((2456873j,0s,0n),+0s,2299161j)>}
答案 1 :(得分:0)
我会写这个
File.open 'birthdays.txt', 'r' do |f|
f.read.each_line do |line|
name, date = line.split(/,/, 2)
birth_dates[name] = date.chomp
birth_dates.each_key { |a| birth_dates[a].strip! }
end
如下:
File.open 'birthdays.txt', 'r' do |f|
f.read.each_line do |line|
name, date = line.split(/,/, 2)
birth_dates[name] = date.chomp.strip
end
end
或
birth_dates = File.readlines('birthdays.txt').with_object({}) do |line,hsh|
name, date = line.split(/,/, 2)
hsh[name] = date.chomp.strip
end