14
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.

4

5 回答 5

18

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

于 2013-01-29T04:19:42.603 回答
10

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.

于 2016-10-21T01:17:18.210 回答
5

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

于 2018-12-28T17:06:35.730 回答
2

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. :)

于 2013-01-29T08:31:32.843 回答
0

Ruby doesn't have parameter type verification, though you can add sugar method to all objects for convenience to verify type like this:

def doSomething(value)
   print value.should_be(Numeric) * 2
end

or

def initialize(fruit)
   @fruit = fruit.should_be(Fruit)
end
Object.class_eval do

  def should_be cls
    hide_from_stack = true
    if self && !self.is_a?(cls)
      raise("Expected class #{cls}, got #{self.class}")
    end
    self
  end

end
于 2021-05-09T07:49:04.583 回答