------ art_20394_9351059.1204050749167 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Tue, Feb 26, 2008 at 9:09 AM, John Wilger <johnwilger / gmail.com> wrote: > On Feb 24, 8:57 pm, Eric Mahurin <eric.mahu... / gmail.com> wrote: > > I don't see the big advantage of Array#to_csv over a more traditional > > CSV::from_a(arr), other than a few more characters to type. It is much > more > > encapsulated. > > The big advantage is that, when writing a method that needs to receive > CSV data as an argument, you don't have to do type checking on the > argument - any object that responds correctly to the #to_csv message > can be used. > > def i_need_csv( obj ) > data bj.to_csv > do_something_with( data ) > end > > This gives more freedom to the user of the library who might have an > object of their own class which knows how to turn itself into CSV > data. Your suggestion would lead to something like: > > def i_need_csv( obj ) > data ase obj > when Array > CSV::from_a( obj ) > when Hash > CSV::from_hash( obj ) > else > raise "Sorry, I'm not duck-type friendly!" > end > end > > Yuck. Point taken. Monkey patching might be the best solution in this situation. Assuming you want to be able to convert any arbitrary object to a CSV, this might be best. Another possibility would be something like this: module CSV From Array proc {|a| ...} Hash proc {|h| ...} ... } ... Then use CSV::From[obj]. The problem is that if you build a class later that wants to work with CSV, you'd need to modify this CSV::From "global". This "global" modification isn't much better than monkey patching "global" modification. I think John does illustrate why monkey patching can be useful with duck-typing. In statically-typed languages (like C++), the above can be solved by overloading a global function based on type (type should prevent collisions). Don't take this to mean I want static-typing. I'm the biggest fan duck-typing. Still, we should not use monkey patching as our first tool. We should think of it just like global variable modification, IMO. Eric ------ art_20394_9351059.1204050749167--