2015-02-11 19 views
-1

我有一個名爲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的值時。

+0

我不認爲這是合理的打印你的對象時,IRB調用inspect。如你所知,#新是一個構造函數。構造函數總是返回該類的一個實例。所以你的想法是毫無意義的。 – freemanoid 2015-02-11 07:51:55

回答

0

您是不是要找這個?:

Test = Struct.new('Test', :a, :b) 
example = Test.new(1, 2) 
example.instance_eval do 
    def give_me_some_stuff 
    a + b 
    end 
end 

example.give_me_some_stuff #=> 3 
another_example = Test.new(1, 2) 
# => #<struct Struct::Test a=1, b=2> 
another_example.give_me_some_stuff 
#=> NoMethodError: undefined method `give_me_some_stuff' for #<struct Struct::Test a=1, b=2> 
2

example總是返回你的對象。如果它會返回另一個對象,則example.give_me_some_stuff將不再起作用。

也許您在尋找inspect

class Test 
    def inspect 
    "I am Test" 
    end 
end 

IRB會議:

irb(main):001:0> example = Test.new 
=> I am Test 
irb(main):002:0> example 
=> I am Test 
+0

這適用於字符串,但如果我將它放在那裏,它將不會返回實例方法的值。我已經用我試圖通過的確切代碼更新了這個問題。 – Corey 2015-02-11 14:58:16

+0

@Corey'inspect'應該返回一個字符串。在你的例子中,返回'@ contents.inspect'應該可以工作。 – Stefan 2015-02-11 15:03:49