0

In the Cadence SKILL (proprietary EDA language, based on LISP & SCHEME), one can define the argument types in a procedure.
It will error out if the wrong type of argument is given. See shell report below:

procedure( foo( ko "t" ) printf( "Hey %s\n" ko ) )
>foo
>foo("1")
>Hey 1
>t
foo(1)
>*Error* foo: argument #1 should be a string (type template = "t") - 1

Is there something as nifty as that in Ruby? That is, in the method interface definition, not the body, the type checking is done?
Thanks.

user1134991
  • 3,003
  • 2
  • 25
  • 35

2 Answers2

1

You can make it "nifty" like this:

module FirstArgumentIsAString
  module Initializer
    def initialize(word)
      fail 'Word must be String' unless word.is_a?(String)
      super
    end
  end

  def self.included(klass)
    klass.send :prepend, Initializer
  end
end

class Foo
  include FirstArgumentIsAString
end

y = Foo.new(2)
> Uncaught exception: Word must be String
Mike S
  • 324
  • 1
  • 10
0

You can always do

fail 'Keep input as a string' unless variable_name.is_a?(String)

while it is not dynamic typing language way of thinking, try to achieve duck-typing

Mike S
  • 324
  • 1
  • 10