TestFirst 레슨에서는 문자열을 Fixnum으로 강제 변환할 수 없습니다.

StackOverflow https://stackoverflow.com//questions/25045302

  •  21-12-2019
  •  | 
  •  

문제

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

줄에 repetition + " " + say, 당신은 다음을 시도하고 있습니다 연쇄 사이 Fixnum 그리고 String 오류를 일으킨 인스턴스 문자열을 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top