Search code examples
rubyruby-hash

Ruby hash only return TRUE


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

Solution

  • 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