有人可以向我解释我的代码

时间:2016-06-16 17:58:18

标签: ruby

class Book
attr_accessor :title
    def title=(book_name)
        small_words = ["and", "in", "the", "of", "a", "an"]
        words = book_name.split(' ')
        words.each do |word| 
            small_words.include?(word) ? word : word.capitalize! 
        end
        words[0].capitalize!
        @title = words.join(' ')
    end
end

所以我一直在学习Ruby并且一直在做一些Ruby测试。这个是为了除了''之外的所有图书标题,''''等等。我理解其中的大部分内容,除了几件事。 在阅读错误后,我可以看到它想要一个名为Book的类,所以我就这样做了。为什么需要这个? 然后attr_accessor :title@title = words.join(' ')结尾。我理解他们的意思,但他们为什么需要?

1 个答案:

答案 0 :(得分:3)

基本上我们说你的输入(book_name)是“cthulhu的召唤”。

words = book_name.split(' ')

分为“the”,“call”,“of”,“the”,“cthulhu”。

words.each do |word| 
    small_words.include?(word) ? word : word.capitalize! 
end

迭代数组并将所有单词大写除了small_words中的单词。数组现在有“the”,“Call”,“of”,“the”,“Cthulhu”。

words[0].capitalize!

将第一个词大写。所以现在数组有“The”,“Call”,“of”,“the”,“Cthulhu”。

@title = words.join(' ')

用一个单词(Cthulhu的调用)连接数组并将其设置在title -instance变量中,该变量在Ruby中使用@ -syntax在类中引用。

attr_accessor为标题创建一个setter和一个getter,当不在类中时需要它。

x = book.title # x is now "The Call of the Cthulhu"
book.title = "New Title" # sets the title to a new String