我正在使用Ruby1.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}
发布于 2015-08-06 17:09:45
好,拿着你的帽子:
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
上抛出正则表达式和散列,它将搜索正则表达式的每一个匹配项,查找匹配的"hits“作为哈希键,并将值替换回字符串中:
gsub(pattern, hash) → new_str
...If第二个参数是哈希,匹配的文本是它的键之一,对应的值是替换字符串.
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文档很好地涵盖了这一切。
这个功能是在Ruby中制作一个非常高速的模板程序的核心。
发布于 2015-08-06 14:25:54
首先,遵循命名约定。变量是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]}
发布于 2015-08-06 15:00:41
你可以这样做:
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."
https://stackoverflow.com/questions/31866688
复制相似问题