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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With