Ruby Case 类检查

标签 ruby class case

如何让以下代码工作(我想根据参数的类决定操作):

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

最佳答案

case 语句中的比较是通过 === 完成的 - 也称为 case 相等运算符。对于 StringFixnum 等类,它被定义为测试对象是否是该类的实例。因此,只需删除 .class 方法调用即可将实例传递给比较,而不是类:

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

附加说明:在您的示例中,您将 case block 的结果分配给局部变量 material,该变量在 block 之后立即返回。这是不必要的,您可以立即返回 block 的结果,这使得该方法有点短:

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

关于Ruby Case 类检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43957892/

相关文章:

ruby-on-rails - 有没有可以比较或解析多种语言的工具?

ruby 的 :yields:

javascript - 反墨迹

bash - "If fi"内的 "case esac"

Oracle CASE 短路不能按组工作

mysql - 在 Sequel 中编写复杂的 case 语句?

ruby-on-rails - PG::UndefinedTable: 错误:关系 "services"不存在 LINE 1: SELECT "services".* FROM "services"

html - "fa fa-commenting"和 "fa fa-user-plus"这两个类不起作用

python - 朴素贝叶斯分类(使用 NLTK)

sql - 具有 NULL 值的 CASE 表达式