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).
我正在尝试在ruby中构建一个相对简单的应用程序。但是当我调用了obj.to_s时,我无法让我的对象返回0以外的任何东西。我理解代码的质量可能很差(并且不介意任何提示)。
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
1 个解决方案
#1
3
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:
因为您定义了类方法to_s而不是实例1。在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 Read any book about Ruby and any styleguide like Githubbers or bbatsov one.
PS阅读任何关于Ruby的书和任何样式指南,如Githubbers或bbatsov one。
#1
3
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:
因为您定义了类方法to_s而不是实例1。在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 Read any book about Ruby and any styleguide like Githubbers or bbatsov one.
PS阅读任何关于Ruby的书和任何样式指南,如Githubbers或bbatsov one。