29
def my_method(parameter) if <what should be here?> puts "parameter is a string" elsif <and here?> puts "parameter is a symbol" end end 

5 Answers 5

50

The simplest form would be:

def my_method(parameter) puts "parameter is a #{parameter.class}" end 

But if you actually want to do some processing based on type do this:

def my_method(parameter) puts "parameter is a #{parameter.class}" case parameter when Symbol # process Symbol logic when String # process String logic else # some other class logic end end 
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't that be case parameter.class?
@Beerlington I just tested, and it works fine using only parameter.
@Beerlington: No: in a case x; when y ....; end, Ruby runs y === x to determine if it should enter the when block. === is just defined to do something "useful"; for instance, for classes, it's instance_of?; for ranges, it's include?, etc.
Some more insight into case parameter.class issue.
25
def my_method(parameter) if parameter.is_a? String puts "parameter is a string" elsif parameter.is_a? Symbol puts "parameter is a symbol" end end 

should solve your issue

Comments

14
if parameter.is_a? String puts "string" elsif parameter.is_a? Symbol puts "symbol" end 

I hope this helps.

Comments

2
def my_method(parameter) if parameter.is_a? String puts "parameter is a string" elsif parameter.is_a? Symbol puts "parameter is a symbol" end end 

Comments

1
if parameter.respond_to? id2name p "Symbol" else p "not a symbol" 

This will also work , but not an elegant solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.