Ruby Case类检查 [英] Ruby Case class check

查看:70
本文介绍了Ruby Case类检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使以下代码工作(我想根据arg的类决定一个动作):

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

推荐答案

case语句中的比较是使用===完成的-也称为大小写相等运算符.对于像StringFixnum这样的类,它定义为测试对象是否是该类的实例.因此,通过删除.class方法调用来将类传递给比较对象,而不是类:

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

在您的示例中,将case块的结果分配给局部变量material,该变量在该块之后立即返回.这是不必要的,您可以立即返回该块的结果,这会使该方法变得更短:

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

这篇关于Ruby Case类检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆