Can I tell a Ruby method to expect a specific parameter type?

前端 未结 4 2259
旧时难觅i
旧时难觅i 2021-02-20 06:46
def doSomething(value)
    if (value.is_a?(Integer))
        print value * 2
    else
        print \"Error: Expected integer value\"
        exit
    end
end

4条回答
  •  鱼传尺愫
    2021-02-20 07:42

    You can raise an Exception anytime arbitrarily if you deem it necessary.

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

    Whether or not you really want to do this is a separate issue. :)

提交回复
热议问题