Ruby 有人能解释一下我的代码吗
所以我一直在学习Ruby并做了一些Ruby测试。这本书将所有书名大写,除了“and”、“in”、“the”和“e.t.c”。我理解其中的大部分,除了几件事。 在阅读了这些错误之后,我发现它需要一个名为Book的类,所以我这样做了。为什么需要这样做?Ruby 有人能解释一下我的代码吗,ruby,Ruby,所以我一直在学习Ruby并做了一些Ruby测试。这本书将所有书名大写,除了“and”、“in”、“the”和“e.t.c”。我理解其中的大部分,除了几件事。 在阅读了这些错误之后,我发现它需要一个名为Book的类,所以我这样做了。为什么需要这样做? 然后使用@title=words的attr\u访问器:title。在末尾加入(“”)。我理解它们的意思,但为什么需要它们呢?基本上,让我们假设您的输入(书名)是“cthulhu的召唤” 拆分为“the”、“call”、“of”、“the”、“cthu
然后使用
@title=words的attr\u访问器:title
。在末尾加入(“”)
。我理解它们的意思,但为什么需要它们呢?基本上,让我们假设您的输入(书名)是“cthulhu的召唤”
拆分为“the”、“call”、“of”、“the”、“cthulhu”数组
迭代数组并将除小词中的词以外的所有单词大写。数组现在有“the”、“Call”、“of”、“the”、“Cthulhu”
首字母大写。所以现在数组有“the”,“Call”,“of”,“the”,“Cthulhu”
在一个单词(Cthulhu的调用)中加入数组,并在title-instance变量中设置它,该变量在Ruby中用类中的@语法引用
@title = words.join(' ')
attr_访问器为标题创建一个setter和一个getter,当标题不在类中时,需要使用它
@title = words.join(' ')
你认为为什么需要它们?在我的脑海中,我已经创建了一个名为Book的文件夹,在这个文件夹中我有一个名为title的文件,我可以在上面读写。不确定这是否正确。不过,
@标题
让我很反感。我知道@
将它链接到属性访问器
,但为什么不干脆title=words.join(“”)
,因为title=words.join(“”)
将创建一个局部变量title,而不是写入该“文件”。你也可以做self.title=words.join(“”)
words.each do |word|
small_words.include?(word) ? word : word.capitalize!
end
words[0].capitalize!
@title = words.join(' ')
x = book.title # x is now "The Call of the Cthulhu"
book.title = "New Title" # sets the title to a new String