Question

I'm trying to pass an rspec and normally I would do a method and pass a function in. All I have to do is add one, I'm embarrassed I'm even posting here...

normally I would do

def adder(n)
   n+1
end

However I need to pass in a block and I'm not familiar with it.

describe "adder" do
 it "adds one to the value returned by the default block" do
  adder do
    5
  end.should == 6
 end

 it "adds 3 to the value returned by the default block" do
   adder(3) do
    5
  end.should == 8
 end
end

I tried

    def adder
       yield  {|n| return n+1 }
    end
Était-ce utile?

La solution

The following code will do:

def adder(a=1, &block)
  a + yield
end
 => :adder 

adder do
  5
end
 => 6 

adder(3) do
  5
end
 => 8

You need to learn how to pass a block as parameter and default values for methods

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top