argument How to check in Ruby if method's parameter is a symbol?




ruby optional block argument (4)

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

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

This will also work , but not an elegant solution.


Answer #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

Answer #3

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

Answer #4
if parameter.is_a? String
  puts "string"
elsif parameter.is_a? Symbol
  puts "symbol"
end

I hope this helps.







ruby