From: Rick DeNatale Date: 2008-01-18T06:02:40+09:00 Subject: Re: Properly using Ruby's specialness On 1/17/08, James Gray wrote: > 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 > * DSL I think that rather than sparingly, the adverb should be carefully. Open classes are very powerful in situations like building a framework, (e.g. Rails). Features such as plugins, use formalized patterns of extending open classes to allow opening classes while minimizing the potential for collisions. > > 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 Right, another is to accomplish what the OP did by adding an instance to Array in a safer more controlled fashion. Rather than "duck punching" all now and future instance of Array we can specialize particular instances. > > 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 -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/