Instructions
Create two functions:
all_positive?(numbers)- returns true if ALL numbers are positiveany_negative?(numbers)- returns true if ANY number is negative
Use the all? and any? methods:
ruby
[1, 2, 3].all? { |n| n > 0 } # => true
[1, -2, 3].any? { |n| n < 0 } # => true
Hints:
- all? returns true only if block is true for every element
- any? returns true if block is true for at least one element
- Empty array: all? returns true, any? returns false
Your Code
def all_positive?(numbers)
numbers.all? { |n| n > 0 }
end
def any_negative?(numbers)
numbers.any? { |n| n < 0 }
end
RSpec.describe "all? and any?" do
describe "all_positive?" do
it "returns true when all positive" do
expect(all_positive?([1, 2, 3])).to be true
end
it "returns false when one negative" do
expect(all_positive?([1, -2, 3])).to be false
end
it "returns true for empty array" do
expect(all_positive?([])).to be true
end
end
describe "any_negative?" do
it "returns true when one negative" do
expect(any_negative?([1, -2, 3])).to be true
end
it "returns false when all positive" do
expect(any_negative?([1, 2, 3])).to be false
end
it "returns false for empty array" do
expect(any_negative?([])).to be false
end
end
end
Results
Click "Run Tests" to see results
1 / 5
Next: Group By