2013-03-25 147 views
0

我只是想知道是否有更美麗的方法來創建對象的方法並返回它?從方法創建並返回對象

這裏是我的代碼:

class Example 
    def Example.load_from_file(filename) 
    example = Example.new 
    # some code 
    example 
    end 
end 

可能有一些紅寶石成語,讓我不要在方法的末尾寫example。你可以重構這段代碼,或者它現在足夠了嗎?

回答

1

假設你有example是可變的,你繼續申請「一些代碼」中的破壞性的方法它:

class Example 
    def Example.load_from_file(filename) 
    Example.new.tap do |example| 
     # some code 
    end 
    end 
end 
+0

感謝。這是我需要的:) – demas 2013-03-25 07:26:29