gpt4 book ai didi

ruby - 本地跳转错误 : no block given

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:36 25 4
gpt4 key购买 nike

我在运行 rspec 文件时不断收到错误:

Failures:                                                                                                                                  

1) Book title should capitalize the first letter
Failure/Error: @book.title("inferno")
LocalJumpError:
no block given (yield)
# ./08_book_titles.rb:7:in `title'

这是 book_title.rb

class :: Book

attr_accessor :some_title

def title(some_title)
little_words = %w(of and for the over under an a but or nor yet so at around by after along from on to with without)
some_title = yield
some_title.split.each_with_index.map{|x, index| little_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
end #def

end

这是 rspec 文件(或至少是第一个规范):

require_relative '08_book_titles'

describe Book do

before do
@book = Book.new
end

describe 'title' do
it 'should capitalize the first letter' do
@book.title("inferno")
@book.title.should == "Inferno"
end
end

我已将 yield 包含在方法中,规范中有一个 block ...所以我不明白为什么它不调用该 block 。我已经尝试了所有我能想到的方法,从直接在 map 上调用它(而不是使用分配给它的变量)到单独调用它然后在 map 上使用它,再到尝试将它作为标题的参数传递在方法中......到你现在看到的。我还阅读了大量线程。我没看到什么?

我看到 future 的练习也将在自定义类上运行规范,所以我也喜欢一些提示(或链接),这些提示(或链接)是我在使用 rspec 测试自定义类时需要了解或注意的事情。谢谢!

更新

所以我将 book_title.rb 更改为如下所示:

  class :: Book

def title
little_words = %w(of and for the over under an a but or nor yet so at around by after along from on to with without)
self.split.each_with_index.map{|x, index| little_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
end #def

end

因为我可能错误地编辑了规范 - 我将它们还原为:

require '08_book_titles'

describe Book do

before do
@book = Book.new
end

describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
@book.title.should == "Inferno"
end
end

我现在得到的错误是:

Failure/Error: @book.title = "inferno"                                                                                                
NoMethodError:
undefined method `title=' for #<Book:0x007f292a06c6b0>
# ./08_book_titles_spec.rb:26:in `block (3 levels) in <top (required)>'

最佳答案

您误用了 yield 不,规范中没有任何 block 。如果有,规范看起来像...

  @book.title("inferno") do
"inferno"
end

看到我添加的 block 了吗?但是你不需要一个 block ,你不应该使用 yield

您似乎认为您需要 yield 来访问参数……您不需要。你的 title 方法应该直接使用传递的参数......

def title(new_title)
little_words = %w(of and for the over under an a but or nor yet so at around by after along from on to with without)
@some_title = new_title.split.each_with_index.map{|x, index| little_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
end #def

最后,您的测试实际上调用了 title 方法两次,而您应该只调用一次并使用 attr_accessor 方法来测试结果。

it 'should capitalize the first letter' do
@book.title("inferno")
@book.some_title.should == "Inferno"
end

关于ruby - 本地跳转错误 : no block given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com