2013-04-09 47 views
-2

對不起,我的英語。Ruby - 對象類的別名

我的代碼...

class MyClass 

    NewFood = Food 

    def index 
    @items = NewFood.all 
    end 
end 

@items.first是食品的對象,但我希望得到一個NewFood對象

一些幫助?

回答

1

拿這個例子:

class Foo 
    @@instances = [] 

    def initialize(value) 
    @value = value 
    @@instances << self 
    end 

    def self.all 
    @@instances 
    end 
end 

class Bar 
    NewFoo = Foo.dup 

    def index 
    @items = NewFoo.all 
    end 
end 

# Now Bar::NewFoo will instantiate it's own objects 
Bar::NewFoo.new(5) 
Bar::NewFoo.new('fish') 
Bar.new.index 
=> [#<Bar::NewFoo:0x00000002f33cf0 @value=5>, 
    #<Bar::NewFoo:0x00000002f65958 @value="fish">] 

但是我看不到這類元編程黑客的需要。
編輯:廢話,我忘了類變量(@@var)共享沿着它的孩子的,所以這個例子可以把凌亂。

1

它沒有意義的,說你想要一個NewFood對象。只有兩類:MyClassFood。常數MyClass::NewFood只是指向Food;僅僅因爲你定義了這個常數並不意味着你可以期望類的實例開始有不同的表現,並說他們的類是NewFood

你能縮小,並告訴我們的大局是什麼?你想達到什麼目的?你想要解決什麼真正的生活問題?我們可以提供解決問題的更好方法。