Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Can I tell a Ruby method that a certain parameter should be an Integer, otherwise crash? Like Java.

like image 344
Voldemort Avatar asked Jan 29 '13 04:01

Voldemort


3 Answers

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

like image 147
sepp2k Avatar answered Oct 17 '22 16:10

sepp2k


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.

like image 39
Daniel Avatar answered Oct 17 '22 17:10

Daniel


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

like image 8
Gregology Avatar answered Oct 17 '22 16:10

Gregology