Instructions
Create a function group_by_length that takes an array of strings
and returns a hash where keys are string lengths and values are
arrays of strings with that length.
Use the group_by method:
```ruby
["a", "bb", "c"].group_by { |s| s.length }
=> {1 => ["a", "c"], 2 => ["bb"]}
Hints:
- Use .group_by { |word| word.length }
- group_by returns a hash automatically
- Keys are the block return values
Your Code
def group_by_length(words)
words.group_by { |word| word.length }
end
RSpec.describe "group_by_length" do
it "groups words by length" do
result = group_by_length(["hi", "hello", "hey", "world"])
expect(result[2]).to eq(["hi"])
expect(result[3]).to eq(["hey"])
expect(result[5]).to contain_exactly("hello", "world")
end
it "handles empty array" do
expect(group_by_length([])).to eq({})
end
it "handles single word" do
expect(group_by_length(["ruby"])).to eq({ 4 => ["ruby"] })
end
end
Results
Click "Run Tests" to see results