From: ebeard Date: 2006-10-06T03:45:11+09:00 Subject: Re: Better ruby way for caseing on class? Hmmm. This is the most interesting approach. I was not aware of Kernel#lambda. It's been creeping around like a wolfda in lambda's clothing. :) ara.t.howard@noaa.gov wrote: > On Thu, 5 Oct 2006, ebeard wrote: > > > I currently do this: > > > > [Kernel,String,Object].each do |klass| > > case klass.to_s > > when 'Kernel' : > > puts 'I\'m doing stuff with object Kernel' > > when 'String' : > > puts 'I\'m doing stuff with object String' > > when 'Object' : > > puts 'I\'m doing stuff with object Object' > > end > > end > > > > > > Is there a better way? > > well, the code you have above is exactly equivalent to this > > [Kernel, String, Object].each{|k| puts "I'm doing stuff with object #{ k }"} > > but i suppose your real code is quite different? my point is just that > looping over three things and selecting them each in turn is the same thing as > pre-selecting the items to loop over. another alternative is > > actions = { > Kernel => lambda{ puts "I\'m doing stuff with object Kernel"}, > String => lambda{ puts "I\'m doing stuff with object String"}, > Object => lambda{ puts "I\'m doing stuff with object Object"}, > } > > [Kernel, String, Object].each{|k| actions[k].call} > > which works for some situations and can sometimes be even more general > > actions = lambda{|k| lambda{ puts "I'm doing stuff with object #{ k }"} } > > [Kernel, String, Object].each{|k| actions[k].call} > > > which is suited to compact arg dependant actions but not long ones. > > regards. > > -a > -- > in order to be effective truth must penetrate like an arrow - and that is > likely to hurt. -- wei wu wei