useeffect
useeffect

Reputation: 59

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

Upvotes: 1

Views: 533

Answers (2)

iGian
iGian

Reputation: 11193

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

Upvotes: 0

max pleaner
max pleaner

Reputation: 26768

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

Upvotes: 2

Related Questions