Ruby 是否支持类型提示? [英] Does Ruby support type-hinting?

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

问题描述

PHP 示例:

function do_something(int $i) {
    return $i + 2;
}

Ruby 示例:

class MyClass
    # ...
end

def do_something(MyClass x)
    x.prop1 = "String..."
end

有类似的吗?谢谢.

推荐答案

Ruby 没有这样的东西,但你所要做的就是添加一行:

Ruby does not have such thing, but all you have to do is add a single line as so:

def do_something(x)
  raise "Argument error blah blah" unless x.kind_of?(MyClass)
  ...
end

没什么大不了的.但是如果你觉得它太冗长了,那就定义一个方法吧:

Not a big deal. But if you feel it is too verbose, then just define a method:

module Kernel
  def verify klass, arg
    raise "Argument error blah blah" unless arg.kind_of?(klass)
  end
end

并将其放在第一行:

def do_something(x)
  verify(MyClass, x)
  ...
end

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

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