Detecting data type

hello all,
i’m new to ruby and need some help on what seems like a simple issue.

How do i find out if the argument passed to a method is a string or an
integer?

Here’s what i’m trying to do:

def method_test(some_arg)
if some_arg is string
#callmethod A
else
#callmethod B
end
end

Thanks for your help.

Parv

On Thu, 19 Oct 2006 22:03:07 +0900
“Parv G.” [email protected] wrote:

#callmethod A

else
#callmethod B
end
end

irb(main):002:0> ‘a’.is_a?(String)
=> true

etc.

– Thomas A.

Thomas A. wrote:

On Thu, 19 Oct 2006 22:03:07 +0900
“Parv G.” [email protected] wrote:

#callmethod A

else
#callmethod B
end
end

irb(main):002:0> ‘a’.is_a?(String)
=> true

etc.

– Thomas A.

Thanks for the quick response.

On Thu, 19 Oct 2006, Parv G. wrote:

hello all,
i’m new to ruby and need some help on what seems like a simple issue.

How do i find out if the argument passed to a method is a string or an
integer?

“It depends” :slight_smile: At the most basic you could look at the class:
x.class
and see what that gives you, but classes are open in Ruby so it
might not be the beast it was at birth. So you really want to
know if it has the right properties for what you are doing. So you
could use
x.respond_to?(:dowcase)
but that really doesn’t tell you much, because the method could be
redefined. In short, you try not to test this sort of thing.
Searth the web for “Duck typing” for more on this issue.

Here’s what i’m trying to do:

def method_test(some_arg)
if some_arg is string
#callmethod A
else
#callmethod B
end
end

Not really, that’s more like what you have done when trying to do
something else. What was your actual goal?
For this case you could use:

if some_arg.respond_to?(:method_a)
some_arg.method_a
else
some_arg.method_b
end

but ideally you want to be sure that your method is called with the
correct type anyway. You could also use some_arg.to_i, some_arg.to_s
to convert to the correct type.

Thanks for your help.

Parv

    Hugh

Parv G. wrote:

#callmethod A

else
#callmethod B
end
end

Not repeating the obvious
duck-type-but-not-really-cause-that-says-nothing-anyway, applying the
“replace conditional with polymorphism” refactoring is probably the
cleanest solution from an OO point of view. More so because this is
trivial with Ruby’s open classes, and the standard library probably has
what you need (like a type conversion method).

David V.