Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

People also ask

Is symbol an object in Ruby?

Symbol is the most basic Ruby object we can create. It's just a name and an internal ID. Since a given symbol name refers to the same object throughout a Ruby program, Symbols are useful and more efficient than strings.

How do you check if a method is defined in Ruby?

When a variable is undefined, it means that it contains no value. We can check if a value is defined or undefined in Ruby using the local_variables. include?(:) method.

What is the difference between string and symbol in Ruby?

There are two main differences between String and Symbol in Ruby. String is mutable and Symbol is not: Because the String is mutable, it can be change in somewhere and can lead to the result is not correct. Symbol is immutable.

How do I check if a string is in Ruby?

In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.


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