Reputation: 21
I'm working on an example problem from Chris Pine's Learn to Program book and I'm having an issue removing white space in my hash values.
I start with a txt file that contains names and birthday information, like so:
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
Then I go through each line, split at the first comma, and then try to go through each key,value to strip the white space.
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
But nothing is getting stripped.
{"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"}
I've seen a handful of solutions for Arrays using .map - but this was the only hash example I came across. Any idea why it may not be working for me?
UPDATE: removed the redundant chomp as per sawa's comment.
Upvotes: 2
Views: 1223
Reputation: 42192
For parsing comma delimited files i use CSV like this
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"}
of if you need real date's you can drop the 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)>}
Upvotes: 2
Reputation: 9762
I would write this
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
as below:
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
or
birth_dates = File.readlines('birthdays.txt').with_object({}) do |line,hsh|
name, date = line.split(/,/, 2)
hsh[name] = date.chomp.strip
end
Upvotes: 0