Instructions
Create a function anagram? that returns true if two strings
are anagrams of each other (contain the same letters).
- Ignore case
- Ignore spaces
Example: anagram?("listen", "silent") returns true
Hints:
- Remove spaces and downcase both strings
- Sort the characters and compare
- str.gsub(' ', '').downcase.chars.sort
Your Code
def anagram?(str1, str2)
normalize = ->(s) { s.gsub(" ", "").downcase.chars.sort }
normalize.call(str1) == normalize.call(str2)
end
RSpec.describe "anagram?" do
it "returns true for listen/silent" do
expect(anagram?("listen", "silent")).to be true
end
it "is case insensitive" do
expect(anagram?("Listen", "Silent")).to be true
end
it "ignores spaces" do
expect(anagram?("rail safety", "fairy tales")).to be true
end
it "returns false for non-anagrams" do
expect(anagram?("hello", "world")).to be false
end
end
Results
Click "Run Tests" to see results