def my_method(parameter)
if <what should be here?>
puts "parameter is a string"
elsif <and here?>
puts "parameter is a symbol"
end
end
Asked
Active
Viewed 2.7k times
27

Misha Moroshko
- 166,356
- 226
- 505
- 746
5 Answers
49
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

SLaks
- 868,454
- 176
- 1,908
- 1,964
-
1Shouldn't that be `case parameter.class`? – Peter Brown Dec 12 '10 at 14:49
-
@Beerlington I just tested, and it works fine using only parameter. – Thiago Silveira Dec 12 '10 at 15:39
-
12@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. – Antal Spector-Zabusky Dec 12 '10 at 15:42
-
Some more [insight](http://stackoverflow.com/questions/3908380/ruby-class-types-and-case-statements) into `case parameter.class` issue. – x-yuri Jan 10 '15 at 14:16
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

Raghu
- 2,543
- 1
- 19
- 24
14
if parameter.is_a? String
puts "string"
elsif parameter.is_a? Symbol
puts "symbol"
end
I hope this helps.

Conner
- 30,144
- 8
- 52
- 73

Saif al Harthi
- 2,948
- 1
- 21
- 26
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

Rekin
- 9,731
- 2
- 24
- 38
1
if parameter.respond_to? id2name
p "Symbol"
else
p "not a symbol"
This will also work , but not an elegant solution.

sunny1304
- 1,684
- 3
- 17
- 30