From: James Gray Date: 2008-01-18T05:14:54+09:00 Subject: Re: Properly using Ruby's specialness On Jan 17, 2008, at 1:04 PM, J. Cooper wrote: > 1. Open classes. The other day, in a little Blackjack game I wrote in > Ruby, I used this feature to add in a method to the Array class > instead > of making a class that inherited from Array and added that method. > However, a) I'm not sure if that was the "right" way and b) I'm not > sure > if there is an advantage to that approach over the latter, per se. Open classes are best used sparingly. There are problems with them, of course, in that your code might collide with someone else's code. The plus though is that all instances of the changed class are suddenly empowered with new methods you can count on. Some good uses, in my opinion, are: * Conversion methods – I would rather type %w[a b c].to_csv than CSV.generate_line(%w[a b c]. I don't feel there's much danger of namespace collision here either due to the specific types in the method names. Some disagree and feel this is polluting the namespace though. * DSL – It can often be convenient to make Ruby understand the language of your problem rather than to express your problem in Ruby. > 2. Singleton methods. I really can't think of a particular example > where > I would use this... please help! Well, technically you use this feature in Ruby anytime you create a class method. Outside of that, it's another feature best used in moderation. It does have interesting possibilities though. Here's an example to try and get you thinking in new directions: >> def add_counts(array) >> counts = array.inject(Hash.new(0)) { |c, e| c.merge(e => c[e] + 1) } >> class << array; self; end.send(:define_method, :counts) do ?> counts >> end >> end => nil >> a = Array.new(10) { rand(6) } => [2, 3, 3, 3, 0, 2, 4, 3, 4, 3] >> add_counts(a) => # >> a.counts => {0=>1, 2=>2, 3=>5, 4=>2} > 3. Blocks. Although now (after some practice and getting used to) > these > make sense to me when I use them with methods already designed, I > don't > think I have internalized them to the point where I would write my own > methods that accepted them and worked with them. Has anyone else > been in > the same boat, or do they usually just "click"? I wrote about this on my blog a while back. Maybe it will help: http://blog.grayproductions.net/articles/code_as_a_data_type James Edward Gray II James Edward Gray II