Instructions
Create two functions that demonstrate the key difference between
procs and lambdas: argument checking.
strict_add- uses a lambda (checks argument count)lenient_add- uses a proc (ignores extra arguments)
Lambdas are created with:
```ruby
->(a, b) { a + b }
or
lambda { |a, b| a + b }
```
Both should add two numbers, but:
- Lambda raises ArgumentError if wrong number of args
- Proc ignores extra args or uses nil for missing
Hints:
- Use ->(a, b) { a + b } for lambda
- Use Proc.new { |a, b| a + b } for proc
- Both return callable objects
Your Code
def strict_add
->(a, b) { a + b }
end
def lenient_add
Proc.new { |a, b| a.to_i + b.to_i }
end
RSpec.describe "Lambda vs Proc" do
describe "strict_add (lambda)" do
it "adds two numbers" do
expect(strict_add.call(2, 3)).to eq(5)
end
it "raises error with wrong arg count" do
expect { strict_add.call(1) }.to raise_error(ArgumentError)
end
it "is a lambda" do
expect(strict_add.lambda?).to be true
end
end
describe "lenient_add (proc)" do
it "adds two numbers" do
expect(lenient_add.call(2, 3)).to eq(5)
end
it "handles missing args" do
expect(lenient_add.call(5)).to eq(5) # nil.to_i = 0
end
it "is not a lambda" do
expect(lenient_add.lambda?).to be false
end
end
end
Results
Click "Run Tests" to see results