質問

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
.

そしてここでそれを除外するレーキテストは次のように設定されています:

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

私はエラーメッセージが数値のような文字列を使うことを試みることについてのものであることを理解していますが、私はそれがどのように起こっているか、どこで起こっているのか見えないことを理解しています

役に立ちましたか?

解決

以下は問題源

です。
repetition = repetition + " " + say
#              ^ this is a Fixnum
.

Line repetition + " " + sayでは、FixnumStringインスタンス間の連結を実行しようとしています。これは、エラー文字列を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 file: -

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
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top