Monday, September 22, 2008

Dynamic programming advantage

Want to show you some pieces of Ruby code that do the same thing.

Original version:
FIELDS = [ 'first', 'last',      'band' ]
DATA = [['Kurt', 'Cobain', 'Nirvana'],
['Jimi', 'Page', 'Led Zeppelin'],
['Noel', 'Gallagher', 'Oasis'],
['Thom', 'Yorke', 'Radiohead']]

def combine_fields_and_data(fields, data)
new_data = []
data.each do |row|
row_hash = {}
row.each_with_index do |column, i|
row_hash[fields[i].to_sym] = column
end
new_data.push(row_hash)
end
return new_data
end

Small_logo

And Adam's refactoring

def combine_fields_and_data(fields, data)
data.map { |row| Hash[*fields.zip(row).flatten] }
end

Adam code utilize Ruby built-in Array and Hash utilities that make his code extremely short.

Read more about Array utilities here.

No comments: