Ruby-使用map和大写方法大写标题

问题描述 投票:0回答:2

我正在研究Odin Projects Ruby基础知识,并完全停留在05_book_titles上。标题必须大写,包括第一个单词,但不包括“小单词”(即“ to”,“ the”等),除非它是第一个单词。除了大写外,我无法获得执行任何其他操作的代码。我在滥用地图方法吗?如何获取不包含首字母大写的no_cap单词?

Ruby文件:

class Book
def title
    @title
end 

def title=(title)
    no_cap = ["if", "or", "in", "a", "and", "the", "of", "to"]
    p new_title = @title.split(" ")
    p new_new_title = new_title.map{|i| i.capitalize if !no_cap.include? i}
.join(" ") 
end
end

某些规范文件:

require 'book'

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      expect(@book.title).to eq("Inferno")
    end

    it 'should capitalize every word' do
      @book.title = "stuart little"
      expect(@book.title).to eq("Stuart Little")
    end

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

        specify 'a' do
          @book.title = "to kill a mockingbird"
          expect(@book.title).to eq("To Kill a Mockingbird")
        end

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

      specify 'conjunctions' do
        @book.title = "war and peace"
        expect(@book.title).to eq("War and Peace")
      end
    end
  end
end

结果:

Book
  title
    should capitalize the first letter (FAILED - 1)

Failures:

  1) Book title should capitalize the first letter
     Failure/Error: @book.title = "inferno"

     NoMethodError:
       undefined method `split' for nil:NilClass
     # ./05_book_titles/book.rb:8:in `title='
     # ./05_book_titles/book_titles_spec.rb:25:in `block (3 levels) in <top (required)>'

Finished in 0.0015 seconds (files took 0.28653 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./05_book_titles/book_titles_spec.rb:24 # Book title should capitalize the first letter
ruby class methods getter-setter
2个回答
0
投票

您在分配@title之前正在使用它

new_title = @title.split(" ")

应更改为title

@title方法结束时,您不将计算出的标题分配给title=

您还需要在no_cap上添加“ an”,以便通过以“每天吃一个苹果”为标题的规范。

并注意第一个单词:

class Book
  def title
      @title
  end 

  def title=(title)
      no_cap = ["if", "or", "in", "a", "and", 'an', "the", "of", "to"]
      new_title = title.split(' ').each_with_index.map do |x, i|
          unless i != 0 && no_cap.include?(x)
            x.capitalize
          else
            x
          end
      end

      @title = new_title.join(' ')
  end
end

0
投票

small_words = [ “ if”,“ or”,“ in”,“ a”,“ and”,“ the”,“ of”,“ to”] >> ]

str = "tO be      Or Not to be."

str.gsub(/\p{Alpha}+/) { |s| Regexp.last_match.begin(0) > 0 &&
  small_words.include?(s.downcase) ? s.downcase : s.capitalize }
  #=> "To Be      or Not to Be."
© www.soinside.com 2019 - 2024. All rights reserved.