Can I say that the Ruby method expects a certain type of parameter?

def doSomething(value)
    if (value.is_a?(Integer))
        print value * 2
    else
        print "Error: Expected integer value"
        exit
    end
end

Is it possible to tell the Ruby method that a certain parameter must be Integer, otherwise crash? Like Java.

+5
source share
3 answers

No, you can’t. You can only do what you already do: check the type yourself.

+10
source

I'm late to the party, but I wanted to add something else:

Ruby Duck Typing. , , , . , (*). , .

- Ruby #responds_to?, #is_a?

, .

+4

You can throw an exception at any time arbitrarily if you consider it necessary.

def doSomething(value)
    if (value.is_a?(Integer))
        print value * 2
    else
        raise "Expected integer value"
    end
end

Regardless of whether you want to do this, this is a separate issue. :)

+2
source

All Articles