Ruby 字符串可以';在第一课的测试中,不要强制使用Fixnum

Ruby 字符串可以';在第一课的测试中,不要强制使用Fixnum,ruby,rake-test,test-first,Ruby,Rake Test,Test First,我正在阅读TestFirst.org教程,收到一条无法解开的错误消息: Failure/Error: repeat("hello").should == "hello hello" TypeError: String can't be coerced into Fixnum # ./03_simon_says/simon_says.rb:13:in `+' # ./03_simon_says/simon_says.rb:13:in `block in repeat' # ./03

我正在阅读TestFirst.org教程,收到一条无法解开的错误消息:

 Failure/Error: repeat("hello").should == "hello hello"
 TypeError:
   String can't be coerced into Fixnum
 # ./03_simon_says/simon_says.rb:13:in `+'
 # ./03_simon_says/simon_says.rb:13:in `block in repeat'
 # ./03_simon_says/simon_says.rb:12:in `times'
 # ./03_simon_says/simon_says.rb:12:in `repeat'
 # ./03_simon_says/simon_says_spec.rb:39:in `block (3 levels) in <top (required)>'
这里是启动它的rake测试:

it "should repeat a number of times" do
  repeat("hello", 3).should == "hello hello hello"
end

我知道错误消息是关于尝试使用类似于数值的字符串,但我看不出这是如何发生的,也看不到发生的位置。下面是问题的根源

repetition = repetition + " " + say
#              ^ this is a Fixnum
在第
repeation+“”+say
行中,您试图在
Fixnum
String
实例之间进行连接,这导致错误字符串无法强制转换为Fixnum

在我的test_spec.rb文件中:-

让我们运行测试:-

arup@linux-wzza:~/Ruby> rspec spec/test_spec.rb
.

Finished in 0.00129 seconds (files took 0.1323 seconds to load)
1 example, 0 failures
arup@linux-wzza:~/Ruby>
更新

repetition = say
how_many = how_many-1
  how_many.times do |repetition|
如果您认为,
重复
在块外部和块内部声明是相同的,那么您完全错了。它们是不同的,因为它们是在两个不同的作用域中创建的。请参见以下示例:-

var = 2
2.times { |var| var = 10 } # shadowing outer local variable - var
var # => 2

谢谢我在Sublime中找不到单步函数,所以知道它在谈论哪个变量很有帮助,但是“重复”是如何变成Fixnum的呢?输入“say”是一个字符串,我想我是在声明“repeation”是一个字符串值,等于“say”。@allightholder Look
你做了多少次| repeation
好吧,这就是我想知道的。我假设两次重复都是同一个对象,但我不确定。
require_relative "../test.rb"

describe "#repeat" do
  it "returns 'hello' 3 times" do
    expect(repeat('hello', 3)).to eq('hello hello hello')
  end
end
arup@linux-wzza:~/Ruby> rspec spec/test_spec.rb
.

Finished in 0.00129 seconds (files took 0.1323 seconds to load)
1 example, 0 failures
arup@linux-wzza:~/Ruby>
repetition = say
how_many = how_many-1
  how_many.times do |repetition|
var = 2
2.times { |var| var = 10 } # shadowing outer local variable - var
var # => 2