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

前端 未结 4 2260
旧时难觅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:18

    I would suggest a raise unless type match at the beginning of the method

    def do_something(value)
      raise TypeError, 'do_something expects an integer' unless value.kind_of?(Integer)
      ...
    end
    

    This is raise an error and exit unless value is an Integer

提交回复
热议问题