Better ruby way for caseing on class?

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?

On Oct 4, 2006, at 11:10 AM, ebeard wrote:

end
end

Is there a better way?

Sure. Drop the call to to_s() and the ’ … 's around the class
names. Case calls ===() for the condition object and Class defines
===() to do what you expect here.

James Edward G. II

On 10/4/06, James Edward G. II [email protected] wrote:

when ‘Object’ :

James Edward G. II

His example is more strict: it will match only for Object object,
while yours will match any Object.

(in other words, the OP checks for identity, while you check for class
membership)

On 04.10.2006 18:08, ebeard wrote:

end
end

Is there a better way?

Use the other form of “case”:

[Kernel,String,Object].each do |klass|
case
when klass == Kernel :
puts ‘I’m doing stuff with object Kernel’
when klass == String :
puts ‘I’m doing stuff with object String’
when klass == Object :
puts ‘I’m doing stuff with object Object’
end
end

robert

On Thu, 5 Oct 2006, ebeard wrote:

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

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. :slight_smile: