Instructions
Create a function make_multiplier that takes a number and returns
a Proc that multiplies its argument by that number.
Create a Proc with:
```ruby
Proc.new { |x| x * 2 }
or
proc { |x| x * 2 }
or
->(x) { x * 2 } # This is actually a lambda
```
Call a Proc with .call(arg) or .(arg) or [arg].
Example:
ruby
double = make_multiplier(2)
double.call(5) # => 10
Hints:
- Return Proc.new { |x| x * n }
- The proc captures the variable n (closure)
- Procs are objects that wrap blocks
Your Code
def make_multiplier(n)
Proc.new { |x| x * n }
end
RSpec.describe "make_multiplier" do
it "creates a multiplier proc" do
double = make_multiplier(2)
expect(double.call(5)).to eq(10)
end
it "works with different multipliers" do
triple = make_multiplier(3)
expect(triple.call(4)).to eq(12)
end
it "captures the value (closure)" do
times_ten = make_multiplier(10)
expect(times_ten.call(7)).to eq(70)
end
end
Results
Click "Run Tests" to see results
1 / 4
Next: Lambda vs Proc