John Smith
John Smith

Reputation: 6259

Create an new instance of class in Ruby

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!

Upvotes: 1

Views: 153

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

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

Upvotes: 5

Dan Grahn
Dan Grahn

Reputation: 9394

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

attr_accessor :text
attr_accessor :number

See this question

Upvotes: 2

Related Questions