如果字符串中的任何一个Value匹配,我想输出该值
代码:
list = {
"red" => ["apple", "cherry"],
"blue" => ["sky", "cloud"],
"white" => ["paper"]
}
str = "testString"
list.each do |k, v|
puts "string: #{str}"
puts "value: #{v}"
puts /^*#{v}*/.match? str.to_s
end
我期望输出为假,因为没有匹配项
但是实际输出都是正确的。
string: testString
value: String
true
string: testString
value: String
true
string: testString
value: String
true
如果“ testString”匹配任何“值”
如何打印键值?
下面的代码是我的错误代码。
list.each do |k, v|
puts "string: #{str}"
puts "value: #{v}"
if /^*#{v.to_s}*/.match? str
puts "key of value is : #{k}"
end
end
答案 0 :(得分:1)
您的v
变量实际上是一个单词数组。
所以当你说:
if /^*#{v.to_s}*/.match? str
实际上是在做这样的事情:
if /^*["apple", "cherry"]*/.match?(string)
这不是您所需要的。
如果要查看是否有任何个单词匹配,可以使用Array#any?:
list = {
"red" => ["apple", "cherry"],
"blue" => ["sky", "cloud"],
"white" => ["paper"]
}
str = "testString"
list.each do |key, words|
puts "string: #{str}"
puts "value: #{words}"
puts words.any? { |word| /^*#{word}*/.match? str.to_s }
end
打印:
string: testString
value: ["apple", "cherry"]
false
string: testString
value: ["sky", "cloud"]
false
string: testString
value: ["paper"]
false
注意,对我来说,真正的输出还不清楚,但是如果要打印true / false以外的内容,可以这样做:
if words.any? { |word| /^*#{word}*/.match? str.to_s }
puts "its a match"
else
puts "its not a match"
end
答案 1 :(得分:0)
没有正则表达式,因为值是数组,所以可以进行嵌套循环:
list.each do |color, words| # loops through keys and values
puts "\nLooking for #{str} in #{color}"
words.each do |word| # loops through the elements of values
found = (word == str)
puts "\t- #{word} is #{found}"
end
found_any = words.include? str
puts "\tFound any match? #{found_any}"
end
哪个打印出来
# Looking for apple in red
# - apple is true
# - cherry is false
# Found any match? true
#
# Looking for apple in blue
# - sky is false
# - cloud is false
# Found any match? false
#
# Looking for apple in white
# - paper is false
# Found any match? false