Ruby 仅散列 return 真

Ruby hash only return TRUE

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

代码:

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" 匹配任何 "Value"

如何打印值的键?

下面的代码是我的错误代码。

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

你这里的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

没有正则表达式,因为值是数组,你可以做一个嵌套循环:

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