bubai93
bubai93

Reputation: 51

How to match a symbol with a string in Ruby

I have an array that contains both string and symbol

In my function I am getting a string to check if the array contains that or not.

array = ["day",:night]

def check(name)
    if array.include? name or array.include? name.to_sym
         return true
    else
         return false
   end
end

If the input is "day" it returns true. If the input is "night" it returns false. I want to return true in case of "night" as I converted this to check if a symbol with the same name exists.

How can I make this function work so that it compares a symbol (:night) with a string ("night") and returns true?

Upvotes: 0

Views: 3113

Answers (2)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Put your array into your method definition like so:

def check(name)
  array = ["day",:night]
  array.include? name.to_s or array.include? name.to_sym  
end

p check("day") #=> true
p check(:day) #=> true
p check("night") #=> true
p check("hyperspace") #=> false

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

def check(name, array)
  array.map(&:to_s).include?(name.to_s)
end

array = ["day",:night]

check("day", array)   #=> true
check(:day, array)    #=> true
check("night", array) #=> true
check(:night, array)  #=> true
check("cat", array)   #=> false

Upvotes: 5

Related Questions