1

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

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>'

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

4

2 回答 2

5

You have to this :

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

You could write this as below,no need of 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
于 2013-09-09T11:07:07.670 回答
2

You haven't made any accessors for your variables. Add these

attr_accessor :text
attr_accessor :number

See this question

于 2013-09-09T11:07:32.153 回答