Instructions
Ruby has a powerful shorthand for calling a method on each element.
Instead of:
ruby
words.map { |w| w.upcase }
You can write:
ruby
words.map(&:upcase)
The &:method_name converts a symbol to a proc that calls that method.
Create a function lengths that returns the length of each string
in an array using the &:method syntax.
Hints:
- Use .map(&:length)
- &:length is equivalent to { |s| s.length }
- This works with any method that takes no arguments
Your Code
def lengths(strings) strings.map(&:length) end
RSpec.describe "lengths with &:method" do
it "returns length of each string" do
expect(lengths(["hello", "world", "ruby"])).to eq([5, 5, 4])
end
it "handles empty array" do
expect(lengths([])).to eq([])
end
it "handles empty strings" do
expect(lengths(["", "a", "ab"])).to eq([0, 1, 2])
end
end
Results
Click "Run Tests" to see results