Using a class object in case statement

后端 未结 4 1249
梦如初夏
梦如初夏 2020-12-15 09:09

What is the best way to use a class object in case statement? Suppose I have a which is an instance of the Class class. I want to match it against

4条回答
  •  無奈伤痛
    2020-12-15 09:18

    The problem with using something like this:

    case a.to_s
    when "String" then ...
    when "Fixnum" then ...
    end
    

    is that it completely misses subclasses so you can get something that is a String but is missed by your first branch. Also, name would be a better choice than to_s since semantically, you're testing the class's name rather than its string representation; the result may be the same but case a.name would be clearer.

    If you want to use a case and deal with subclassing then you could use Module#<= like this:

    case
    when a <= String then ...
    when a <= Fixnum then ...
    end
    

    Yes, you have to repeat a in each when but that's just how case works.

提交回复
热议问题