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

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

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

    A really important concept in Ruby is Duck Typing. The idea behind this principle is that you don't really care about the types of your variables, as far as they can do what you want to do with them. What you want in your method is to accept a variable that responds to (*). You don't care about the class name as far as the instance can be multiplied.

    Because of that, in Ruby you will see more often the method #responds_to? than #is_a?

    In general, you will be doing type assertion only when accepting values from external sources, such as user input.

提交回复
热议问题