Luke Dickety
Luke Dickety

Reputation: 7

Why does my to_s method return 0 in ruby?

I'm trying to build a relatively simple app in ruby. However I am unable to get my object to return anything other than 0 when puts obj.to_s is called on it. I understand the quality of the code may be poor (and wouldn't mind any hints).

Help please!

class Docpart
  def Docpart.new(inputAsString,typeAsInteger)
@value = inputAsString
@type = typeAsInteger.to_i # 0 = title, 1 = text, 2 = equation (can't be done yet), 3 = table
  end

  def Docpart.to_s
return "Type is #{@type}, value is #{@value}"
  end
end

module Tests
  def Tests.test1()
filetree = Array.new(0) 
filetree.push( Docpart.new("Title",0))
filetree.each{|obj| puts obj.to_s}
return filetree[0]
  end
end

puts Tests.test1.to_s
gets.chomp

Upvotes: 0

Views: 477

Answers (1)

Hauleth
Hauleth

Reputation: 23586

Because you defined class method to_s not instance one. Also writing constructor in Ruby is a little different. You need to write this that way:

class Docpart
  def initialize(inputAsString,typeAsInteger)
    @value = inputAsString
    @type = typeAsInteger.to_i # 0 = title, 1 = text, 2 = equation (can't be done yet), 3 = table
  end

  def to_s
    "Type is #{@type}, value is #{@value}"
  end
end

module Tests
  def self.test1
    filetree = []
    filetree << Docpart.new("Title",0)

    filetree.each{ |obj| puts obj.to_s }

    filetree[0]
  end
end

puts Tests.test1.to_s
gets.chomp

PS Read any book about Ruby and any styleguide like Githubbers or bbatsov one.

Upvotes: 3

Related Questions