【问题标题】:String can't be coerced into Fixnum in TestFirst lesson在 TestFirst 课程中,字符串不能被强制转换为 Fixnum
【发布时间】:2014-09-22 14:17:28
【问题描述】:

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

我知道错误消息是关于尝试使用像数值这样的字符串,但我看不出这是如何发生的或发生在何处

【问题讨论】:

    标签: ruby rake-test test-first


    【解决方案1】:

    以下是问题来源

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

    在repetition + " " + say 行中,您试图在Fixnum 和String 实例之间进行连接,这导致错误String can't be coerced into 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
    

    【讨论】:

    • 谢谢。我在 Sublime 中找不到分步功能,所以知道它在谈论哪个变量会有所帮助 但是“重复”如何成为 Fixnum?输入“say”是一个字符串,我以为我在声明“repetition”是一个等于“say”的字符串值。
    • @alightholder 从这里看how_many.times do |repetition| 1.times do |repetition| .. 因此Fixnum#times 每次迭代只将Fixnum 对象放入块中。
    • 好的,这就是我想知道的。我曾假设两次重复是同一个对象,但我不确定。
    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多