Ruby中Object的变量更改方法

时间:2012-08-27 14:50:40

标签: ruby oop class variables object

我有一个名为Movie的课程:

class Movie 
    attr_accessor :title, :director, :date_of_issue, :register_number
    def initialize(title, director, date_of_issue, register_number)
        @title, @director, @date_of_issue, @register_numver = title, director, date_of_issue, register_number
    end
    def Basic_info
        puts "Title : #{@tytul}, Director: #{@autor}"
    end
end 

我想创建一个方法来更改现有Movie对象的变量,而不创建一个全新的对象。可能吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

你不需要一种方法,你在正确的轨道上,纠正了一些错误

class Movie  
  attr_accessor :title, :director, :date_of_issue, :register_number 
  def initialize(title, director, date_of_issue, register_number) 
    @title, @director, @date_of_issue, @register_numver = title, director, date_of_issue, register_number 
  end 
  def basic_info 
    puts "Title : #{@title}, Director: #{@director}" 
  end 
end  

movie = Movie.new "title", "director", "", 0
movie.director = "Martin Scorsese"
movie.title = "Goodfellas"
movie.date_of_issue = "1990"
movie.basic_info

#=>Title : Goodfellas, Director: Martin Scorsese