2014-04-09 59 views
0

我有類A與方法X和Y.現在我想創建一個實例,但只希望它有類A的方法X.如何使用Ruby中的類的部分方法創建實例?

我應該怎麼做?是否應該在創建實例時刪除方法Y?感謝您的幫助!

+4

這是一個奇怪的事情做。你想要解決什麼問題? –

+0

正如@RenatoZannon所說,這很奇怪。我懷疑你應該重構並使用一個模塊。 'Module ModuleWithX'和'Module ModuleWithY',然後在你的新類中包含ModuleWithX' – Automatico

回答

1

你不應該這樣做。你應該分享你正在解決的問題,找到解決問題的更好的模式。


的有點不同解決這個問題的一個例子:

class A 
    def x; end 
end 

module Foo 
    def y; end 
end 

instance_with_y = A.new 
instance_with_y.send :include, Foo 
instance_with_y.respond_to? :y #=> true 
1

這是可能做到你想要紅寶石什麼,紅寶石可以是這樣的可塑性很大,但也有很多更好的方法。你想達到什麼似乎是一個非常糟糕的主意。

剛剛描述的問題繼承的問題旨在解決。所以真的,你有兩個班。類別A以及繼承自類別A的類別B

class A 
    def foo 
    'foo' 
    end 
end 

# B inherits all functionality from A, plus adds it's own 
class B < A 
    def bar 
    'bar' 
    end 
end 

# an instance of A only has the method "foo" 
a = A.new 
a.foo #=> 'foo' 
a.bar #=> NoMethodError undefined method `bar' for #<A:0x007fdf549dee88> 

# an instance of B has the methods "foo" and "bar" 
b = B.new 
b.foo #=> 'foo' 
b.bar #=> 'bar' 
1

這是解決問題的一種方法:

class X 
    def a 
    11 
    end 
    def b 
    12 
    end 
end 

ob1 = X.new 
ob1.b # => 12 
ob1.singleton_class.class_eval { undef b } 
ob1.b 
# undefined method `b' for #<X:0x9966e60> (NoMethodError) 

,或者你可以爲寫(上面和下面都是一樣的):

class << ob1 
    undef b 
end 

ob1.b 
# undefined method `b' for #<X:0x93a3b54> (NoMethodError) 
相關問題