2013-09-02 4 views
0

나는이 문자와 정말 흡사하다고 느끼지만 왜 .join이 작동하지 않는지 알 수 없습니다.문자열을 대소 문자로 변환

이 내가 쓴 코드입니다 :

class String 
    def title_case 
    title = self.split 
    title.each do |word| 
     unless (word.include?("of")) || (word.include?("the")) && (title.first != "the") 
     word.capitalize! 
     end 
    title.join(" ") 
    end 
    end 
end 

는 그리고 이것은 RSpec에 있습니다 : 당신이 코드의 형식이 경우, 당신은 당신이 #join 전화를 잘못 볼 것

describe "String" do 
    describe "Title case" do 
    it "capitalizes the first letter of each word" do 
     "the great gatsby".title_case.should eq("The Great Gatsby") 
    end 
    it "works for words with mixed cases" do 
     "liTTle reD Riding hOOD".title_case.should eq("Little Red Riding Hood") 
    end 
    it "ignores articles" do 
     "The lord of the rings".title_case.should eq("The Lord of the Rings") 
    end 
    end 
end 

답변

2

. 루프는 each 외부에 있어야합니다.

def title_case 
    title = self.split 
    title.each do |word| 
    unless (word.include?("of")) || (word.include?("the")) && (title.first != "the") 
     word.capitalize! 
    end 
    end 
    title.join(" ") 
end 

그러나 (@의 xdazz의 대답 등) map 및 비파괴 capitalize를 사용하여 더 관용적 인 것이다. 사용 .map 대신 .each

2

: 당신은 each에 호출의 값을 반환하는

class String 
    def title_case 
    title = self.split 
    title.each do |word| 
     unless (word.include?("of")) || (word.include?("the")) && (title.first != "the") 
     word.capitalize! 
     end 
     title.join(" ") 
    end # End of each 
    end # End of def 
end 

:

class String 
    def title_case 
    title = self.split 
    title.map do |word| 
     unless (word.include?("of")) || (word.include?("the")) && (title.first != "the") 
     word.capitalize 
     end 
    end.join(" ") 
    end 
end 
1

(미묘한) 재 들여 쓰기의 비트는 문제를 보여줍니다. 해결 방법은 을 each의 끝에서 한 줄 아래로 이동 한 다음 메서드 정의가 끝나기 전에 이동하는 것입니다.

관련 문제