[英]Why does my to_s method return 0 in ruby?
I'm trying to build a relatively simple app in ruby. 我正在尝试在ruby中构建一个相对简单的应用程序。 However I am unable to get my object to return anything other than 0
when puts obj.to_s
is called on it. 但是,当在其上puts obj.to_s
时,我无法使我的对象返回除0
以外的任何0
。 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
Because you defined class method to_s
not instance one. 因为您定义的类方法to_s
不是实例一。 Also writing constructor in Ruby is a little different. 在Ruby中编写构造函数也有所不同。 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 . PS阅读有关Ruby的任何书籍以及Githubbers或bbatsov这样的任何样式指南 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.