我有一個名爲Test
的類。我創建了一個實例:如何僅使用實例名稱返回值
example = Test.new
我想,當我鍵入此返回值:
example
我懂得回報打字時的值:
example.give_me_some_stuff
但我無法弄清楚如何重寫實例名稱並返回一些值,最好是類內部方法的結果。
編輯:
這適用於返回一個字符串的方法,但我不能從類的實例返回一個實例變量。例如,下面是我試圖讓工作測試:
def test_push
stack = Stack.new
stack.push(10)
binding.pry
refute stack.empty?
end
,這裏是我的課:
class Stack
attr_accessor :contents
def inspect
@contents
end
def initialize
@contents = []
end
def push(n)
@contents << n
end
end
在測試我的對象回來爲:
#<Stack:0x007f8cd9051938 @contents=[10]>
當我希望它只返回@contents的值時。
我不認爲這是合理的打印你的對象時,IRB調用
inspect
。如你所知,#新是一個構造函數。構造函數總是返回該類的一個實例。所以你的想法是毫無意義的。 – freemanoid 2015-02-11 07:51:55