Instructions
Create a function first_long_word that returns the first word
longer than 5 characters from an array.
Use the find method (also called detect):
ruby
[1, 2, 3].find { |n| n > 1 } # => 2
find returns the first matching element, or nil if none found.
Hints:
- Use .find { |word| word.length > 5 }
- find returns nil if no match
- It stops searching after first match
Your Code
def first_long_word(words)
words.find { |word| word.length > 5 }
end
RSpec.describe "first_long_word" do
it "finds first word longer than 5 chars" do
expect(first_long_word(["hi", "hello", "programming", "ruby"])).to eq("programming")
end
it "returns nil when no match" do
expect(first_long_word(["a", "bb", "ccc"])).to be_nil
end
it "returns first match, not all matches" do
expect(first_long_word(["short", "medium", "another"])).to eq("medium")
end
it "handles empty array" do
expect(first_long_word([])).to be_nil
end
end
Results
Click "Run Tests" to see results