Quantcast

Ruby on Rails, Io, Lisp, JavaScript, Dynamic Languages, Prototype-based programming and more...

Technoblog reader special: $10 off web hosting by FatCow!

Wednesday, August 22, 2007

Really Useful Ruby Mysql One Liner

Mysql::Result.send(:include, Enumerable)
This one line makes interfacing with mysql results SO much easier.
require "mysql"
my = Mysql::new("host", "user", "passwd", "db")
res = my.query("select * from tbl")
res.each do |row|
col1 = row[0]
col2 = row[1]
end
This is from the standard documentation for the Ruby Mysql lib. What does it do? It grabs all items from tbl, and sets col1 and col2 to the first and second column of the LAST value of the result set. Not very useful unless you add a LIMIT 1 to your SQL statement. Much more useful would be this modified code.
require "mysql"
Mysql::Result.send(:include, Enumerable)
my = Mysql::new("host", "user", "passwd", "db")
res = my.query("select first_name, last_name from users")
full_names = res.map do |row|
"#{row[0]} #{
row[1]}"
end
Here we select all users from the table and end up with an array of full name strings. How did including Enumerable help us at all? It defined the map function for us, which natively does not exists for Mysql::Result objects. Why Enumerable is not included in the Mysql::Result class is a mystery to me.

You should follow me on twitter here.

Technoblog reader special: click here to get $10 off web hosting by FatCow!

 

If you like this blog, you might also like top photography schools.