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!

2 Answers 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
Sign up to request clarification or add additional context in comments.

3 Comments

also note the initialiser does nothing at the moment
@JanDvorak I can't edit the line you mentioned.. There is some lock in the post. :(
You've got a typo on the second line of your first code example. attr_accessor.
2

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

attr_accessor :text
attr_accessor :number

See this question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.