Ruby 与加法器默认块练习。我如何根据我的方法是否得到块来改变输出?
以下是我需要通过的rspec:Ruby 与加法器默认块练习。我如何根据我的方法是否得到块来改变输出?,ruby,closures,block,default,yield,Ruby,Closures,Block,Default,Yield,以下是我需要通过的rspec: 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 这是我的代码 d
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
这是我的代码
def adder(&block)
if block.call == 5
block.call + 1
else
block.call + 3
end
end
我的错误输出
加法器
将一个值添加到默认块返回的值中
将3添加到默认块返回的值(失败-1)
失败:
1) 一些愚蠢的块函数加法器在默认块返回的值上加3
故障/错误:加法器(3)do
参数错误:
参数数目错误(1代表0)
#/05_愚蠢的块/愚蠢的块。rb:5:inadder'
#/05愚蠢的块/愚蠢的块规范rb:37:in
块(3级)in'您传递了一个意外的参数:
adder(3) do
5
end
当加法器定义为完全不接收参数时:
def adder(&block)
您应该向加法器定义中添加一个可选参数
def adder(num=1, &block)
block.call + num
end
非常感谢。这绝对是丢失的钥匙!我把num=1和&块的顺序也弄混了。谢谢你的澄清!
def adder(num = 1)
yield + num
end