From: Robert Klemme Date: 2004-10-11T20:24:38+09:00 Subject: Re: [Q] case based on object class "Robert Klemme" schrieb im Newsbeitrag news:2sv8kcF1q3732U1@uni-berlin.de... > > "George Moschovitis" schrieb im Newsbeitrag > news:ckdn7c$2eim$1@ulysses.noc.ntua.gr... > > > I am not sure what you want to do... do you want to separate these > > > things by class and print out the corresponding symbol? > > > > i want to execute different code depending on the klass (Class) object > > given to the method. > > > > > Anyhow, I tried your code and it worked fine for me. I substituted > > > 4 for obj and commented the ... of course. > > > > the code works, I am wondering if there is a more elegant/efficient > > way to write it. > > The OO way is to use a mapping IMHO: I forgot to mention that this is also more efficient if you have many classes. > ACTION_MAPPING = { > Fixnum => lambda { puts "Fixnum" }, > Float => lambda { puts "Float" }, > String => lambda { puts "String" }, > } > > def myfunc(klass) > code = ACTION_MAPPING[klass] > raise ArgumentError, "Klass not found: #{klass}" unless code > code.call > end > > You can even define a block for the error as default effectively rendering > the method a one liner like this: > > ACTION_MAPPING = Hash.new( lambda { raise ArgumentError, "Klass not > found" } ).update( > Fixnum => lambda { puts "Fixnum" }, > Float => lambda { puts "Float" }, > String => lambda { puts "String" } > ) > > def myfunc(klass) ACTION_MAPPING[klass].call end And then there is also the option to define those methods as singleton methods of the classes although I recommend to do this *only* if the functionality is general enough and has to do with the class more than with your app. Kind regards robert