在Ruby中创建一个新的类实例

时间:2013-09-09 11:05:35

标签: ruby

我是编程的初学者,写了一个简单的程序:

class Chapter
  def initialize
@text
@number
  end
end

def new_chapter
  tmp_chapter = Chapter.new
  tmp_chapter.text = 'Chapter about ..'
  tmp_chapter.number = '11'
end

puts new_chapter
puts ObjectSpace.each_object(Chapter) {|x| p x}

但是我收到了这个错误:

 test2.rb:10:in `new_chapter': undefined method `text=' for #<Chapter:0x200b830>
 (NoMethodError)
 from test2.rb:14:in `<main>'

那我做错了什么?我知道还有其他方法可以创建一个新实例,但我想这样做!谢谢!

2 个答案:

答案 0 :(得分:5)

你必须这样:

class Chapter
 attr_accessor :text, :number
 def initialize
  @text
  @number
 end
end

你可以写如下,不需要def initialize ;@text; @number; end

class Chapter
 attr_accessor :text,:number
end
def new_chapter
 tmp_chapter = Chapter.new
 tmp_chapter.text = 'Chapter about ..'
 tmp_chapter.number = '11'
end

puts new_chapter
puts ObjectSpace.each_object(Chapter) {|x| p x}
# >> 11
# >> #<Chapter:0x9596eac @text="Chapter about ..", @number="11">
# >> 1

答案 1 :(得分:2)

您尚未为变量创建任何访问器。添加这些

attr_accessor :text
attr_accessor :number

See this question

相关问题