0

我正在尝试用 ruby​​ 构建一个相对简单的应用程序。但是,除了调用它的时间之外0,我无法让我的对象返回任何内容。puts obj.to_s我了解代码的质量可能很差(并且不介意任何提示)。

请帮忙!

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
4

1 回答 1

3

因为您定义了类方法to_s而不是实例一。用 Ruby 编写构造函数也有点不同。你需要这样写:

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 阅读任何关于 Ruby 的书和​​任何风格指南,例如Githubbersbbatsov one

于 2013-02-20T22:02:09.143 回答