On Feb 6, 2009, at 8:32 AM, Mmcolli00 Mom wrote:
Can this be done with Ruby? (this may be a shot in the dark)
Anything can be done with Ruby. ![:wink: :wink:](/images/emoji/apple/wink.png?v=6)
Say you have a text file with a lot of data and you want to group
all of
your data by a specific value. Is there a way to code something in
ruby
similar to a query that you would create using sql. Can this even be
done using Ruby? And if so, is there a library that you can refer me
to?
If not, do you know any alternative ways? Thanks, MC
I’ll show some pure Ruby code below that seems to do what you want,
but if you really want a query language you have several options.
Personally, I would use the Amalgalite gem to get SQLite. You would
then just read the data and write it into a database. You can then
query it in anyway you like.
how i’d like it to look:
car, honda, nissan,
truck, chevy, toyota, ford
Here’s some code that does that:
#!/usr/bin/env ruby -wKU
headers = DATA.gets.strip.split(/,\s*/)
related = { }
DATA.each do |row|
fields = Hash[headers.zip(row.strip.split(/,\s/)).flatten]
(related[fields[“auto”]] ||= [ ]) << fields[“model”]
end
related.keys.sort.each do |key|
puts(([key] + related[key]).join(", "))
end
END
auto, model
car, honda
truck, chevy
car, nissan
truck, toyota
truck, ford
Hope it helps.
James Edward G. II