Reputation: 2080
I am having some trouble getting a rspec test to pass. My method has passed all the other tests for it except the last one which requires that a word/hash pair be returned if the keyword matches the argument or if the keyword has the same prefix (if a prefix is the argument). In the latter case, If there is more than one match, then the returned hash should include them all. As is, the code that I have is returning the entire hash, so it seems that maybe the regex is not being compared? I have tried multiple ways of doing this but here are two, the first one being what I reverted back to because it has passed the most tests.
def find(word)
returns = {}
if @entries.empty?
@entries
else
@entries.select{|key, value| if key.scan(/word/) then @entries[key] = value end }
end
end
which returned the fail:
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 ==)
My next attempt:
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
returned the fail:
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",
What is the best way to use a regex to get this code to pass? And why isn't my current code passing?
While there are a total of 4 test blocks concerning the find method, is the one (the 4th) that I am having the troubles with:
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
Upvotes: 0
Views: 503
Reputation: 54984
I think you're looking for:
@entries.select{|key, value| key[/#{word}/] }
Upvotes: 2