Dariusz G. Jagielski
Dariusz G. Jagielski

Reputation: 665

How to make sure method have certain type in ruby

As you probably know, ruby, like most scripting languages is dynamically-typed. How can I make sure parameter passed to my method is instance of specific class?

Upvotes: 0

Views: 93

Answers (3)

Dave Newton
Dave Newton

Reputation: 160191

Check its type.

That said, why? In general you should be caring about its duckitude, not its type. I'm generally suspicious when something is tied to its type rather than its messages.

Upvotes: 3

mechanicalfish
mechanicalfish

Reputation: 12826

It is up to caller to provide the argument of correct type. It is common in Ruby to raise ArgumentError if the method is called with an argument of unsupported type. Example:

def do_something_with_a_number(number)
  raise ArgumentError, "you have to provide a number" unless number.is_a?(Fixnum)
  ...
end

Upvotes: 1

tckmn
tckmn

Reputation: 59283

Use is_a?:

def your_method(param)
    if param.is_a? String
        # it's a string
    else
        # not a string
    end
end

Or, if you have lots of classes to check, a case statement:

def your_method(param)
    case param
    when String
        # it's a string
    when Array
        # it's an array
    when Rational
        # it's a rational
    # ...
    else
        # it's not any of these classes
    end
end

Upvotes: 1

Related Questions