La stringa non può essere costretta nel fixnum nella lezione di testFirst
-
21-12-2019 - |
Domanda
Sto lavorando attraverso i tutorial di testfirst.org e ho ottenuto un messaggio di errore che non posso districare:
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)>'
.
Ecco il codice che questi errori stanno parlando ("def ripetizione" è la linea 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
.
Ed ecco il test di rastrello che lo ha impostato:
it "should repeat a number of times" do
repeat("hello", 3).should == "hello hello hello"
end
.
Capisco che il messaggio di errore riguarda il tentativo di utilizzare una stringa come un valore numerico, ma non riesco a vedere come o dove sta accadendo
Soluzione
Di seguito è la fonte del problema
repetition = repetition + " " + say
# ^ this is a Fixnum
.
Nella linea repetition + " " + say
, si sta tentando di eseguire una concatenazione tra un'istanza Fixnum
e String
, che ha causato l'errore String non può essere costretto a 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 >
.
Il tuo codice può essere scritto come:
#!/usr/bin/env ruby
def repeat (say, how_many = 1)
("#{say} " * how_many).strip
end
.
in my 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
.
consente di eseguire il 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>
.
Aggiornamento
repetition = say
how_many = how_many-1
how_many.times do |repetition|
.
Se si ritiene, repetition
dichiarato al di fuori del blocco e all'interno del blocco sono stesso , sei completamente errato .Sono diversi, come hanno creato in 2 diversi ambiti.Vedi il seguente esempio: -
var = 2
2.times { |var| var = 10 } # shadowing outer local variable - var
var # => 2
.