Skip to content

Instantly share code, notes, and snippets.

@jkeck
Created March 10, 2010 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkeck/328592 to your computer and use it in GitHub Desktop.
Save jkeck/328592 to your computer and use it in GitHub Desktop.
# Entering in tabs as \t so that it's easier to understand where the tab
mybuffer = "1\tabc\txyz\tjan1
\tdef\tlmn\tfeb1
2\tamy\tmorgan\tmay1
\tnick\tcary\tmay6"
test_hash = {}
gid = ""
#Split on new line so each line
mybuffer.split(/\n/).each do |line|
#split the line on the \t (tab) character so that we have 4 columns (groupid, first name, last name, birthday)
columns = line.split(/\t/)
# if the first column (group id) is just an empty space then set the gid to the existing group id
if columns.first == " "
gid = gid
else # else set the gid to the first column (gid)
gid = columns.first
end
# if the hash has an item with a key of the group id
if test_hash[gid]
# add another person to the array
test_hash[gid] << {:fname=>columns[1],:lname=>columns[2],:bday=>columns.last}
else
# create a hash item in which the contents is an array with one person in it
test_hash[gid] = [{:fname=>columns[1],:lname=>columns[2],:bday=>columns.last}]
end
end
puts test_hash.inspect
#{"1"=>[{:bday=>"jan1", :fname=>"abc", :lname=>"xyz"}, {:bday=>"feb1", :fname=>"def", :lname=>"lmn"}],
# "2"=>[{:bday=>"may1", :fname=>"amy", :lname=>"morgan"}, {:bday=>"may6", :fname=>"nick", :lname=>"cary"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment