Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created September 20, 2011 07:58
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 rklemme/1228601 to your computer and use it in GitHub Desktop.
Save rklemme/1228601 to your computer and use it in GitHub Desktop.
Solution for thread "array.map! + delete_if possible ?" in ruby-talk
require 'pp'
arr = <<TEXT.scan(/^.*$/)
1201 0 "userid" 1202 0 "lname" 1203 0 "mname" 1204 0 "lname" 1217 0 "password"
4 0 emailaddress
1201 0 "userid" 1202 0 "lname" 1203 0 "mname" 1204 0 "lname" 1217 0 "password"
1201 0 "userid" 1202 0 "lname" 1203 0 "mname" 1204 0 "lname" 1217 0 "password"
TEXT
pp arr
# Solution
# 1. extract fields and create records as Hashes
# record field positions
fields = {} # record field positions
result = [{}] # resulting records
arr.each do |line|
line.scan /(\d+)\s+\d+\s+(?:"([^"]*)"|([a-z]\S*))/i do
# extract data
field = Integer($1)
text = $2 || $3
# record field order
fields[field] ||= fields.size
if result.last[field]
# record complete => add new one
result << {field => text}
else
# record incomplete => set field
result.last[field] = text
end
end
end
pp result
# 2. convert the fields list to an ordered array
fields = fields.sort_by {|k,i| i}.map {|k,i| k}
# 3. convert records to strings
result.map! {|a| fields.map {|k| a[k]}.uniq.join '::'}
pp result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment