Search code examples
rubyclasscase

Ruby Case class check


How can I get the following code to work (I want to decide upon an action based on the class of the arg):

def div arg
  material = case arg.class
             when String
               [arg, arg.size]
             when Fixnum
               arg
             end
  material
end

Solution

  • The comparison in the case statement is done with the === - also called the case equality operator. For classes like String or Fixnum it is defined as testing if the object is an instance of that class. Therefore instead of a class just pass the instance to the comparison by removing the .class method call:

    def div arg
      material = case arg
                 when String
                  [arg, arg.size]
                 when Fixnum
                  arg
                 end
      material
    end
    

    Additional note: In your example, you assign the result of the case block to a local variable material which you return right after the block. This is unnecessary and you can return the result of the block immediately, which makes the method a bit shorter:

    def div(arg)
      case arg
      when String
        [arg, arg.size]
      when Fixnum
        arg
      end
    end