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

时间:2015-01-02 03:49:59

标签: ruby methods

我是一名初学红宝石程序员,正在努力学习。我一直在玩这些我自己编写的代码。我试图在课堂上使用titleize方法,但我收到了错误。当我使用大写方法时,我不会收到错误。我究竟做错了什么?我只是试图将标题字符串中每个单词的第一个字母大写。我正在寻找最简单的答案,不一定是最好或最短的代码。谢谢!

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

1 个答案:

答案 0 :(得分:0)

ruby​​中的String类中没有titleize方法。

您可以将String类扩展为titleize方法或单独使用此函数。

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