【问题标题】:Check the string with hash key使用哈希键检查字符串
【发布时间】:2015-08-07 16:12:48
【问题描述】:

我使用的是 Ruby 1.9。

我有一个哈希:

Hash_List={"ruby"=>"fun to learn","the rails"=>"It is a framework"}

我有一个这样的字符串:

test_string="I am learning the ruby by myself and also the rails."

我需要检查test_string 是否包含与Hash_List 的键匹配的单词。如果是,则将单词替换为匹配的哈希值。

我使用此代码进行检查,但它返回的是空的:

another_hash=Hash_List.select{|key,value| key.include? test_string}

【问题讨论】:

  • a.include? "B" = "B" 是 a 的子串吗?所以你想要的是test_string.include? key

标签: ruby


【解决方案1】:

好的,抓住你的帽子:

HASH_LIST = {
  "ruby" => "fun to learn",
  "the rails" => "It is a framework"
}

test_string = "I am learning the ruby by myself and also the rails."

keys_regex = /\b (?:#{Regexp.union(HASH_LIST.keys).source}) \b/x # => /\b (?:ruby|the\ rails) \b/x
test_string.gsub(keys_regex, HASH_LIST) # => "I am learning the fun to learn by myself and also It is a framework."

Ruby 有一些很棒的技巧,其中之一就是我们如何在gsub 处抛出一个正则表达式和一个哈希,它会搜索正则表达式的每个匹配项,查找匹配的“命中” " 作为哈希中的键,并将值替换回字符串:

gsub(pattern, hash) → new_str

...如果第二个参数是一个Hash,匹配的文本是它的key之一,对应的值就是替换字符串......

Regexp.union(HASH_LIST.keys) # => /ruby|the\ rails/
Regexp.union(HASH_LIST.keys).source # => "ruby|the\\ rails"

请注意,第一个返回一个正则表达式,第二个返回一个字符串。当我们将它们嵌入到另一个正则表达式中时,这一点很重要:

/#{Regexp.union(HASH_LIST.keys)}/ # => /(?-mix:ruby|the\ rails)/
/#{Regexp.union(HASH_LIST.keys).source}/ # => /ruby|the\ rails/

由于?-mix: 标志,第一个可以悄悄地破坏您认为的简单搜索,这最终会在模式中嵌入不同的标志。

Regexp documentation 很好地涵盖了这一切。

此功能是在 Ruby 中制作超高速模板例程的核心。

【讨论】:

    【解决方案2】:

    你可以这样做:

    Hash_List.each_with_object(test_string.dup) { |(k,v),s| s.sub!(/#{k}/, v) } 
     #=> "I am learning the fun to learn by myself and also It is a framework."
    

    【讨论】:

      【解决方案3】:

      首先,遵循命名约定。变量为snake_case,类名为CamelCase

      hash = {"ruby" => "fun to learn", "rails" => "It is a framework"}
      words = test_string.split(' ') # => ["I", "am", "learning", ...]
      another_hash = hash.select{|key,value| words.include?(key)}
      

      回答您的问题:使用#split 将您的测试字符串拆分为单词,然后检查单词是否包含键。

      要检查字符串是否是另一个字符串的子字符串,请使用String#[String] 方法:

      another_hash = hash.select{|key, value| test_string[key]}
      

      【讨论】:

      • 关于“常量是 CamelCase”。类和模块名应该是 CamelCase;其他常量应该在SCREAMING_SNAKE_CASE
      • 很公平,我会修正我的答案。
      • 感谢@EugZol 对命名约定的回答和建议。在我上面的哈希中,您看到还有另一个键“the rails”。是否可以像我们对单个单词一样用字符串检查该键?
      • Ruby 中的变量和方法不是“lower_case”,而是“snake_case”。小写将是“somethinglikethis”。
      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 2020-07-19
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      相关资源
      最近更新 更多