Does Ruby support type-hinting?

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

and put that in the first line:

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

Shameless plug - I just published a ruby gem for this - http://rubygems.org/gems/type_hinting

Usage is here - https://github.com/beezee/ruby_type_hinting

I went looking for it first and found this thread. Couldn't find what I was looking for so I wrote it and figured I'd share here.

I think it's more concise than any of the proposed solutions here and also allows you to specify return type for a method.


Ruby 3 will introduce types to Ruby (Source). You can already use Sorbet now to add types to your ruby code.


If you really want to make sure a certain action is performed on an instance of a specific class (like an integer), then consider defining that action on the specific class:

class Integer
  def two_more
    self + 2
  end
end

3.two_more   #=> 5
2.0.two_more #=> undefined method `two_more' for 2.0:Float (NoMethodError)

class MyClass
  def do_something
     self.prop1 = "String..."
  end
end