[英]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
. 如果输入为“ day”,则返回true
。 If the input is "night" it returns false
. 如果输入为“ night”,则返回false
。 I want to return true
in case of "night" as I converted this to check if a symbol with the same name exists. 我想在“夜晚”的情况下返回true
,因为我将其转换为检查是否存在具有相同名称的符号。
How can I make this function work so that it compares a symbol ( :night
) with a string ( "night"
) and returns true
? 如何使此函数起作用,以便将符号( :night
)与字符串( "night"
)进行比较并返回true
?
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.