Question

Je travaille par le biais de la TestFirst.org tutoriels et ont eu un message d'erreur je ne peux pas vous expliquer:

 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)>'

Voici le code de ces erreurs sont de parler ("def repeat" qui est en ligne 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

Et ici, c'est le râteau test set it off:

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

Je comprends que le message d'erreur est d'essayer d'utiliser une chaîne comme une valeur numérique, mais je ne vois pas comment ni où ce qui se passe

Était-ce utile?

La solution

Ci-dessous est la source du problème

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

Dans la ligne de repetition + " " + say, en essayant de vous faire un concaténation entre un Fixnum et String instance, ce qui a provoqué l'erreur La chaîne ne peut pas être contraint de 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 >

Votre code peut être écrit comme :

#!/usr/bin/env ruby

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

Dans mon test_spec.rb fichier :-

require_relative "../test.rb"

describe "#repeat" do
  it "returns 'hello' 3 times" do
    expect(repeat('hello', 3)).to eq('hello hello hello')
  end
end

Permet d'exécuter le test :-

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>

mise à jour

repetition = say
how_many = how_many-1
  how_many.times do |repetition|

Si vous le pensez, repetition déclarée en dehors du bloc et à l'intérieur de l'îlot sont même, vous êtes complètement mal.Ils sont différents, qu'ils ont créé dans 2 des champs d'application différents.Voir l'exemple ci-dessous :-

var = 2
2.times { |var| var = 10 } # shadowing outer local variable - var
var # => 2
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top