How to check in Ruby if method's parameter is a symbol?
def my_method(parameter)
if <what should be here?>
puts "parameter is a string"
elsif <and here?>
puts "par开发者_开发技巧ameter is a symbol"
end
end
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
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
if parameter.is_a? String
puts "string"
elsif parameter.is_a? Symbol
puts "symbol"
end
I hope this helps.
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
if parameter.respond_to? id2name
p "Symbol"
else
p "not a symbol"
This will also work , but not an elegant solution.
精彩评论