1

我正在阅读 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)>'

这是那些错误正在谈论的代码(“def repeat”是第 09 行)

def repeat (say, how_many=2)
    repetition = say
    how_many = how_many-1

    how_many.times do |repetition|
        repetition = repetition + " " + say
    end

    return repetition
end

这是启动它的 rake 测试:

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

我知道错误消息是关于尝试使用像数值这样的字符串,但我看不到发生的方式或位置

4

1 回答 1

2

以下是问题来源

repetition = repetition + " " + say
#              ^ this is a Fixnum

在该行repetition + " " + say中,您试图在 a和实例之间进行连接,这导致错误String can't be coerced into FixnumFixnumString

2.1.2 :001 > 1 + ""
TypeError: String can't be coerced into Fixnum
        from (irb):1:in `+'
        from (irb):1
        from /home/arup/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
2.1.2 :002 >

您的代码可以写成:

#!/usr/bin/env ruby

def repeat (say, how_many = 1)
  ("#{say} " * how_many).strip
end

在我的test_spec.rb文件中:-

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|

如果你认为,repetition块外声明和块内声明是一样的,那你就大错特错了。它们是不同的,因为它们在2 个不同的范围内创建。请参阅以下示例:-

var = 2
2.times { |var| var = 10 } # shadowing outer local variable - var
var # => 2
于 2014-07-30T19:29:44.987 回答