繁体   English   中英

Ruby:类中的方法拒绝在多行上进行修改

[英]Ruby: Method within a class refuses to be modified over multiple lines

我目前正在做一个rspec ruby​​教程。 其中一个问题要求我写一个book_title程序,该程序利用英语中的一些大写规则。 测试是非常长的,但为了给你一些想法,我已经包括了下面的最后一次测试:

require 'book'

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      @book.title.should == "Inferno"
    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
  end
end

我的代码是:

class Book
    attr_accessor :title

    def initialize(title = nil)
        @title = title
    end

    def title=(book_title = nil)
        stop_words = ["and", "in", "the", "of", "a", "an"]
        @title = book_title.split(" ").each{ |word| 
            unless stop_words.include?(word)
                word.capitalize!
            end}.join(" ").capitalize
    end
end 

我遇到的这个问题是使用def title=方法。 @title = book_title.split (...等)都在一行中,因为当我尝试将其拆分时,我以前的许多测试都失败了。

我试过的一些代码示例:

    @title = book_title.split(" ").each do |word|  # attempting to add words to an array
        unless stop_words.include?(word)           # to capitalize each word
          word.capitalize!
        end
      end
        @title.join(" ")                               # Joining words into one string
        @title.capitalize                              # Capitalizing title's first word
    end                                                # to follow the last test

当我尝试这个测试失败时(我认为这与我在尝试@ title#join和@ title#capitalize时再次调用@title有关)。

其他一些想法:我正在考虑设置第一部分(最后一行以word.capitalize! end end结尾word.capitalize! end end为另一个变量(可能是book_title或new_title)但我想知道甚至初始化或使用@title的原因是什么在第一位。

任何输入,以及更清洁代码的编辑,将不胜感激

你在第二个例子中遇到的问题是Array#each返回调用.each的枚举数,所以在这种情况下你从book_title.split(" ")获得结果(虽然被块修改) 。 您将此结果分配给@title实例变量。 在数组上调用join返回一个字符串,但除了分配它之外,你没有对该字符串做任何事情。 如果你想将它分配给title变量,你需要做@title = @title.join(" ") capitalize相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM