1

I'm a beginner at programming and wrote a simple program:

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}

But I get this error:

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

So what did I do wrong? I know there are other ways to create a new instance but I want to do it this way! Thanks!

Translunar
  • 3,700
  • 31
  • 53
John Smith
  • 5,721
  • 12
  • 49
  • 101

2 Answers2

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
Arup Rakshit
  • 113,563
  • 27
  • 250
  • 306
2

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

attr_accessor :text
attr_accessor :number

See this question

Community
  • 1
  • 1
Dan Grahn
  • 8,638
  • 3
  • 36
  • 71