【问题标题】:Ruby hash only return TRUERuby 哈希仅返回 TRUE
【发布时间】:2019-10-24 10:47:37
【问题描述】:

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

代码:

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的key?

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

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

【问题讨论】:

    标签: ruby ruby-hash


    【解决方案1】:

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

    【讨论】:

    • 好答案。考虑指出/^*["apple", "cherry"]*/.match?(string)/^/.match?(string) 相同,对于任何string,当然是true
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2017-03-21
      • 2021-11-19
      • 2023-03-03
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多