尝试在类中的方法中定义方法

时间:2014-10-10 17:26:29

标签: ruby class methods specifications

我正在尝试传递规范并且我收到错误,“未使用的方法`first_word'为”Inferno“:字符串”

我定义了'first_word'方法,它在类方法'title'中。我无法确定如何在类方法'title'中的字符串上调用这个'first_word'方法。

规范:

描述'标题'     它'应该把第一个字母大写'做       @ book.title =“inferno”       @ book.title.should ==“Inferno”     端

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

1 个答案:

答案 0 :(得分:0)

您在字符串上调用first_word ,类似于"foo".length

您尚未在first_word课程中定义String

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

不相关,但为什么你试图像这样嵌套方法定义?