开发者

case..when for a list of potential ancestors?

If I want to use a case..when to switch based on the kind of an object instance, I can simply do:

case obj
  when Class1
    "whatever"
  when Class2
    "something else"
end

But if the value I'm comparing is a class itself, and I want to switch based on the class it descends from, does case..when still hold up? The following doesn't work, but does anything?

class Foo < String; end
class Bar < Array; end

klass = Foo

case klass
  when String
    "klass descends from String"
  when Array
    "klass descends from Array"
end

Basically what the <= operator does, but in the context of a case..when.

EDIT | Just to clarify, I want to support matching anyw开发者_StackOverflowhere in the inheritance chain, not just the immediate parent.


This works:

case
  when klass <= String
    "klass descends from String"
  when klass <= Array
    "klass descends from Array"
end

I'm not sure if it's any better than a bunch of if and elsif's though.


This works for me, but isn't exactly pretty:

result = case
  when klass.ancestors.include?(String)
    "klass descends from String"
  when klass.ancestors.include?(Array)
    "klass descends from Array"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜