1

If string any of the Value matches, I want to output the value

Code:

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

I expect the output is false because nothing matches

but the actual output is all true..

string: testString
value: String
true
string: testString
value: String
true
string: testString
value: String
true

If "testString" matches any of the "Value"

how can print the key of value?

The code below is my wrong code.

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

2 Answers 2

2

Your v variablere here is actually an array of words.

So when you say:

if /^*#{v.to_s}*/.match? str

that's actually doing something like this:

if /^*["apple", "cherry"]*/.match?(string)

Which is not what you need.

If you want to see if any of the words match, you can use 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

which prints:

string: testString
value: ["apple", "cherry"]
false
string: testString
value: ["sky", "cloud"]
false
string: testString
value: ["paper"]
false

Note, it's not really clear to me what the expected output is, but if you want to print something other than true/false, you can do so like:

if words.any? { |word| /^*#{word}*/.match? str.to_s }
  puts "its a match"
else
  puts "its not a match"
end
1
  • 1
    Good answer. Consider pointing out that /^*["apple", "cherry"]*/.match?(string) is the same as /^/.match?(string), which of course is true for any string. Commented Jun 10, 2019 at 4:32
0

Without regexps, since the values are Arrays, you could do a nested loop:

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

Which prints out

# 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.