Ruby Case class check

霸气de小男生 提交于 2019-12-24 07:49:53

问题


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

回答1:


The comparison in the case statement is done with the === - also called the case equality operator. For classes like String or Fixnum it defined as to test 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

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, what makes the method a bit shorter:

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



回答2:


I think I'd prefer:

def div(arg)
  return arg if arg.is_a? Fixnum
  [arg, arg.size] if arg.is_a? String
end


来源:https://stackoverflow.com/questions/43957892/ruby-case-class-check

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!