2016-12-17 23 views
1

如何使用這門課打印「foo」而不是「foobar」?你不能編輯課程。我今天在考試中找不到的東西

class Test 

    def foo 
     puts "foo" 
     foobar 
    end 

    def foobar 
     puts "foobar" 
    end 

end 

編輯:我只是想出了在那裏你創建一個子類Test並覆蓋foo,以便它只是打印「富」的解決方案。

+0

請務必添加您的解決方案作爲答案! –

+0

我不確定'SubTest.new.foo'是否合格。在我看來,'foo'必須在'Test'的實例上被調用。(btw,而不是在子類中重新定義'foo',你可以在子類中定義一個存根方法'def foobar; end',但這並不能解決我提到的可能的問題。) –

+0

嗯。你可能是正確的,允許使用子類。這可能是問題的提出者想到的。正如@tibsar所建議的,你應該發佈一個答案。 –

回答

3

您可以執行以下操作。

class Test 
    def foo 
    puts "foo" 
    foobar 
    end 
    def foobar 
    puts "foobar" 
    end 
end 

Test.instance_methods(false) 
    #=> [:foo, :foobar] 
Test.new.foo 
    # foo 
    # foobar 

創建的:foobar

Test.class_eval { alias_method :old_foobar, :foobar } 
    #=> Test 
Test.instance_methods(false) 
    #=> [:foo, :foobar, :old_foobar] 
Test.new.old_foobar 
    # foobar 
Test.new.foobar 
    # foobar 

別名創建存根方法:foobar

Test.class_eval { define_method(:foobar) {} } 
    #=> :foobar 

試試吧。

Test.new.foo 
    # foo 

清理

恢復原來:foobar

Test.class_eval { alias_method :foobar, :old_foobar } 
    #=> Test 
Test.new.foo 
    # foo 
    # foobar 

刪除:old_foobar

Test.instance_methods(false) 
    #=> [:foo, :foobar, :old_foobar] 
Test.class_eval { remove_method(:old_foobar) } 
    #=> Test 
Test.instance_methods(false) 
    #=> [:foo, :foobar] 

Test.class_eval { alias_method :old_foobar, :foobar } 

產生相同的別名:old_foobar一樣

class Test 
    alias_method :old_foobar, :foobar 
end 

,但它動態地做到的。

另外,可以寫

Test.send(:alias_method, :old_foobar, :foobar) 

但不

Test.alias_method :old_foobar, :foobar 

因爲:alias_method是私人的。

這些註釋也適用於class_eval的其他兩種用途。

1

您無法編輯該課程。

test = Test.new 
test.foo 
# => foo 
# => foobar 

但是你可以編輯從Test

class << test 
    def foobar 
    end 
end 
test.foo 
# foo 

更多信息,實例化的對象,你可以google 「單態方法」。

相關問題