2014-10-10 83 views
0

我试图让一个规范来传递和我收到一个错误,“未定义的方法`first_word”的‘地狱’:字符串”试图在类中定义的方法中的一个方法

我已经定义了'first_word'方法,它在类方法'title'内。我无法确定如何在类方法“标题”内的字符串上调用此'first_word'方法。

规范:

描述 '标题' 不要 它应该首字母大写“做 @ book.title = ”炼狱“ @ book.title.should == ”地狱“ 结束

it 'should capitalize every word' do 
    @book.title = "stuart little" 
    @book.title.should == "Stuart Little" 
end 

describe 'should capitalize every word except...' do 
    describe 'articles' do 
    specify 'the' do 
     @book.title = "alexander the great" 
     @book.title.should == "Alexander the Great" 
    end 

    specify 'a' do 
     @book.title = "to kill a mockingbird" 
     @book.title.should == "To Kill a Mockingbird" 
    end 

    specify 'an' do 
     @book.title = "to eat an apple a day" 
     @book.title.should == "To Eat an Apple a Day" 
    end 
    end 

    specify 'conjunctions' do 
    @book.title = "war and peace" 
    @book.title.should == "War and Peace" 
    end 

    specify 'prepositions' do 
    @book.title = "love in the time of cholera" 
    @book.title.should == "Love in the Time of Cholera" 
    end 
end 

describe 'should always capitalize...' do 
    specify 'I' do 
    @book.title = "what i wish i knew when i was 20" 
    @book.title.should == "What I Wish I Knew When I Was 20" 
    end 

    specify 'the first word' do 
    @book.title = "the man in the iron mask" 
    @book.title.should == "The Man in the Iron Mask" 
    end 
end 

我的代码:

class Book 
attr_accessor :title 
def initialize 
    @title 
end 
def title=(str) 
    def first_word 
    self[0,1].capitalize + self[1,-1] 
    end 
    cap_except = ["over","and","of","a","to","the","an","or","but","if","else","in"] 
    str = str.split.map {|w| cap_except.include?(w) ? w : w.capitalize}.join(" ").first_word 
    @title = str 
end 

回答

0

您打电话first_word一个字符串,类似于"foo".length

您尚未在String类中定义first_word

您已经定义了一个方法,您可以使用字符串调用,例如first_word("foo")

不相关,但是为什么你想要嵌套像这样的方法定义?

+0

在我自己的教学/学习中,我不确定哪个是最好的方法来获得我想要的结果。所以为了回答你为什么这个问题,诚实的答案是我不确定。我试图创建一个可以在字符串上调用的方法,该字符串可以使字符串的首字母大写,而不会更改字符串的其余部分,并在创建的类中执行此操作。 – 2014-10-11 15:45:32

+0

感谢您为此Dave添加上下文。通过创建另一个类String并在其中定义方法,我可以在一个字符串上调用它 – 2014-10-11 16:14:00

相关问题