使用哈希键检查字符串

时间:2015-08-06 22:13:15

标签: ruby

我使用的是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}

3 个答案:

答案 0 :(得分:0)

首先,遵循命名约定。变量为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]}

答案 1 :(得分:0)

你可以这样做:

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."

答案 2 :(得分:0)

好的,抓住你的帽子:

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,匹配的文本是其中一个键,则相应的值是替换字符串....

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中制作极高速模板程序的核心。

相关问题