tags:

views:

71

answers:

2

The question is in the title.

My parameter can be either a string or a symbol and depending upon which it is I want to perform different actions. Is there a way to check for this in Ruby?

+4  A: 
def foo(arg)
  if arg.is_a?(Symbol)
    do_symbol_stuff
  else
    do_string_stuff
  end
end
sepp2k
Thank you, that's perfect
Damian
There is a nicer way to write this. Use the Class#=== method like this: Symbol === arg. It is much more readable.
johannes
That's a matter of taste of course, but personally I think "if arg is a symbol" reads more naturally than "if arg equals equals equals symbol".
sepp2k
A: 

Another solution

def foo(arg)
  case arg
    when Symbol
      do symbol stuff
    when String
      do string stuff
    else
      do error stuff
  end
end
Scott