【发布时间】:2015-06-17 11:47:51
【问题描述】:
我在通过 rspec 测试时遇到了一些问题。我的方法已经通过了所有其他测试,除了最后一个测试,如果关键字与参数匹配或关键字具有相同的前缀(如果前缀是参数),则需要返回单词/哈希对。在后一种情况下,如果有多个匹配项,则返回的哈希应包含所有匹配项。照原样,我拥有的代码正在返回整个哈希,所以似乎没有比较正则表达式?我已经尝试了多种方法,但这里有两种,第一种是我恢复使用的方法,因为它通过了最多的测试。
def find(word)
returns = {}
if @entries.empty?
@entries
else
@entries.select{|key, value| if key.scan(/word/) then @entries[key] = value end }
end
end
返回失败:
1) Dictionary finds multiple matches from a prefix and returns the entire entry (keyword + definition)
Failure/Error: @d.find('fi').should == {'fish' => 'aquatic animal', 'fiend' => 'wicked person'}
expected: {"fish"=>"aquatic animal", "fiend"=>"wicked person"}
got: {"fish"=>"aquatic animal", "fiend"=>"wicked person", "great"=>"remarkable"} (using ==)
---------------------------------------------- -
我的下一次尝试:
def find(word_or_prefix)
returns = {}
if @entries.empty?
return @entries
else
@entries.select{|key, value| if (/word_or_prefix/ =~ key) then returns << @entries[key] = value end }
end
returns
end
返回失败:
1) Dictionary finds an entry
Failure/Error: @d.find('fish').should == {'fish' => 'aquatic animal'}
expected: {"fish"=>"aquatic animal"}
got: {} (using ==)
Diff:
@@ -1,2 +1 @@
-"fish" => "aquatic animal",
使用正则表达式让此代码通过的最佳方法是什么?为什么我当前的代码没有通过?
虽然关于 find 方法总共有 4 个测试块,但我遇到问题的是一个(第 4 个):
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
【问题讨论】:
-
也许你误解了Hash#select 的作用。
@entries.select { |key, value| <expression> }返回一个包含@entries中所有键值对的哈希,<expression>计算true。因此,例如,在您的第一次尝试中,<expression>是if key.scan(/word/) then @entries[key] = value。顺便说一句,由于@entries[key] == value在计算表达式之前,then部分没有做任何事情。此外,scan也不是最好的;key =~ /word/就足够了。 (续) -
(续)在您的第二次尝试中,您尝试匹配字符串“word_or_prefix”,这可能不是您想要的。
-
假设我们在测试中添加了
@d.add('tiff' => "minor dispute")。该键值对是否应该包含在返回的哈希中? -
您可以在正则表达式中添加“字符串开头”锚
^,使其成为/^#{word}/,或者使用String#begin_with? 方法代替正则表达式。如果您不关心大小写,请写key[/#{word}/i]或key.downcase.start_with?(word)。 -
我用
start_with?把我的情况倒过来了(假设字典都是小写的):key.start_with?(word.downcase)。