在TestFirst课程中,字符串不能被强制转换为Fixnum

时间:2014-07-30 19:27:14

标签: 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_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

我理解错误消息是关于尝试使用类似数值的字符串,但我无法看到发生的方式或位置

1 个答案:

答案 0 :(得分:2)

以下是问题来源

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

在第repetition + " " + say行中,您正在尝试在FixnumString实例之间执行连接,这会导致错误 String can& #39;被强制进入Fixnum

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