Question

PHP Example:

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

Ruby Example:

class MyClass
    # ...
end

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

Is there anything similar to this? Thanks.

Was it helpful?

Solution 2

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

OTHER TIPS

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

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.

No, Ruby itself doesn't support it, and I think that isn't the intention of Matz to add it to the language... Ruby really embraces duck typing in its own internal API and it makes Ruby a very dynamic and productive language...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top