2012-01-05 37 views
1

我們可以用實例方法定義實用類,然後在另一個類中使用實用類的對象調用實例方法嗎?Ruby:如何定義一個util類?

例如,

class Usertype # utility class 
    def add(a, b) 
    c = a + b 
    return c 
    end 
end 

class User 
    user = Usertype.new 

    def test 
    return user.add(1,2) 
    end 
end 

可以這樣做?

回答

6

是的,你可以通過使用模塊實現這一目標:

module Usertype 
    def self.add(a,b) 
    a + b 
    end 
end 
class User 
    def test 
    Usertype.add 1, 2 
    end 
end 
u = User.new 
u.test 
+0

謝謝! MyUtils是定義util類的模塊嗎? – 2012-01-05 17:15:59

+0

那麼,除非你真的需要一個對象,否則你不需要定義一個util類。如果你永遠不需要instanciate,一個模塊很適合包裝常用功能。 – 2012-01-05 17:18:17

+0

是的,我需要從Usertype中調用實例方法,不想直接訪問Usertype,所以我需要一個對象來訪問這些方法。另外,我可以將Usertype定義爲類而不是模塊嗎? – 2012-01-05 17:24:10

1

我不知道你問什麼,但這裏是你可以做什麼:

class Usertype 
    def add(a,b) 
    return a + b 
    end 
end 
class User 
    def test 
    u = Usertype.new 
    return u.add(1,2) 
    end 
end 

或者你可以用一個實例可變用戶:

class User 
    def initialize 
    @u = Usertype.new 
    end 
    def test 
    return @u.add(1,2) 
    end 
end 
+1

我認爲'def'你的意思是'class'。 – meagar 2012-01-05 17:17:13

+0

真夠了:)謝謝。 – 2012-01-05 17:40:10