0

如果字符串中的任何值匹配,我想输出该值

代码:

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
4

2 回答 2

2

您的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

请注意,我并不清楚预期的输出是什么,但如果你想打印除真/假以外的东西,你可以这样做:

if words.any? { |word| /^*#{word}*/.match? str.to_s }
  puts "its a match"
else
  puts "its not a match"
end
于 2019-06-10T03:54:57.233 回答
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
于 2019-06-10T08:04:40.230 回答