在 Ruby 中,我无法让 .titleize 在 class 初始化中工作

In Ruby, I cannot get .titleize to work within the class initialize

我是初学者 ruby 程序员,只是想学习。我一直在玩我自己写的这段代码。我正在尝试在 class 中使用 titleize 方法,但出现错误。当我使用 capitalize 方法时,我没有收到错误。我究竟做错了什么?我只是想将标题字符串中每个单词的首字母大写。我正在寻找最简单的答案,不一定是最好或最短的代码。谢谢!

class Movie
  def initialize(title, rank, year)
    @title = title.titleize
    @rank = rank
    @year = year
  end
  def to_s
    "#{@rank}: #{@title} (#{@year})"
  end
end

movie1 = Movie.new("the godfather", 1, 1972)
movie2 = Movie.new("gladiator", 2, 2000)
movie3 = Movie.new("the godfather part 2", 3, 1974)
movie4 = Movie.new("the dark knight", 4, 2008)
movie5 = Movie.new("return of the jedi", 5, 1983)
movie6 = Movie.new("star wars", 6, 1977)
movie7 = Movie.new("meet joe black", 7, 1998)
movie8 = Movie.new("back to the future", 8, 1985)
movie9 = Movie.new("the bourne identity", 9, 2002)
movie10 = Movie.new("a lot like love", 10, 2005)
movies = [movie1, movie2, movie3, movie4, movie5, movie6, movie7, movie8, movie9, movie10]
puts "Robbie's Top #{movies.size} Movies:"
puts movies

ruby中的Stringclass中没有titleize方法。

您可以扩展字符串 class 以具有 titleize 方法或单独使用此函数。

class String
  def titleize
    self.split(" ").map{|word| word.capitalize}.join(" ")
  end
end