使用Ruby中的正则表达式从散列中查找单词

时间:2022-04-03 15:46:04

I'm doing the Test-First Learn Ruby questions and for the Dictionary question it is asking that a define a method "find" that takes a string as a parameter to search against the keys of a hash containing words and return the key value pairs there the string matches the key. It has to satisfy these situations:

我正在做Test-First Learn Ruby问题,对于Dictionary问题,它要求定义一个方法“find”,它将一个字符串作为参数来搜索包含单词的哈希的键并返回键值对那里的字符串匹配密钥。它必须满足这些情况:

it 'finds multiple matches from a prefix and returns the entire entry (keyword + definition)' do
  @d.add('fish' => 'aquatic animal')
  @d.add('fiend' => 'wicked person')
  @d.add('great' => 'remarkable')
  @d.find('fi').should == {'fish' => 'aquatic animal', 'fiend' => 'wicked person'}
end

My knowledge of regular expressions isn't great. I am at a bit of a loss of what to do here. Help? I think I can pretty well get it to return the key values pairs given that the string an key matches completely, but for this partial matching I am perplexed.

我对正则表达式的了解并不是很好。我有点不知道该怎么做。帮帮我?我认为我可以很好地让它返回键值对,因为字符串键完全匹配,但对于这种部分匹配我很困惑。

1 个解决方案

#1


1  

I'm not sure if you actually need to use regexp here. The test implies that the method will get a string and check it against the hash keys' prefixes. This could be achieved by:

我不确定你是否真的需要在这里使用regexp。测试意味着该方法将获取一个字符串并根据哈希键的前缀进行检查。这可以通过以下方式实现:

def find(string)
  hash.select { |key, value| key.start_with?(string) }
end

Also, Rubular might be a good resource to learn and test regexp

此外,Rubular可能是学习和测试regexp的好资源

#1


1  

I'm not sure if you actually need to use regexp here. The test implies that the method will get a string and check it against the hash keys' prefixes. This could be achieved by:

我不确定你是否真的需要在这里使用regexp。测试意味着该方法将获取一个字符串并根据哈希键的前缀进行检查。这可以通过以下方式实现:

def find(string)
  hash.select { |key, value| key.start_with?(string) }
end

Also, Rubular might be a good resource to learn and test regexp

此外,Rubular可能是学习和测试regexp的好资源