Exercise -extend the RubyCsv class to iterate and return CsvRow objects which you can index via 'method missing'
Again I'm not going to post the complete code, aside from anything else there's a notice at the top saying that it can't be used in articles. For the iteration I mixed in Enumerable, changed @cvs_contents to an attr_reader and defined the 'each' method :
def each
@csv_contents.each { |i| yield i }
end
@cvs_contents isn ow an array of CsvRow objects :
class CsvRowcreated thus :
attr_accessor :contents, :index
def initialize idx,row
@contents = []
@index = idx
@contents = row.split(', ')
end
def method_missing name, *args
@contents[@index.index(name.to_s)]
end
end
@csv_contents.push(CsvRow.new(headers,row.chomp()))I don't really like having the header with each object, and their might be a way around this by creating the class on the fly, populating a class variable with the header list, but see the first paragraph.
What have I learned
Mixin is a powerful concept -but not unique to Ruby. method_missing is a powerful idea -and bloody dangerous. I have achieved the same thing in PHP by overriding __call() and I think that was safer.
Ruby syntax is nice, at least you don't have to scatter ':'s everywhere as you do in Python, it's more consistent than PHP and prettier than Perl5 which generally looks as though a demented spider has been dancing on your keyboard.
No comments:
Post a Comment