2014-05-20 67 views
-1

我被要求做一些函數,然後讓它們作爲String類中的實例方法使用。我如何在Ruby中做到這一點?Ruby字符串中的實例方法?

我在模塊內部做了功能。骨骼是這個東西接近:

module My_module 
def xxxx(string) 
end 
(...) 
end 

class String 
    include My_module 
end 

回答

0

在Ruby中,內置類可以打開和修改這是一個強大的技術,但它被認爲是不禮貌的方法添加到內置類,而不必真的這樣做的充分理由。

你需要做這樣的事情與您的自定義函數(在這裏我定義我的String類中的自定義palindrome功能。

class String 
    # Returns true if the string is its own reverse. 
    def palindrome? 
    self == self.reverse 
    end 
end 

這樣做,你可以直接調用String對象的方法。

爲如:

"level".palindrome? # => true 
+0

謝謝!但是,我應該重新鍵入模塊內部字符串中的相同代碼嗎? – danslz

+0

是的!你有代碼,除了不需要在方法定義中發送一個字符串作爲它在String類中定義的參數。 – uday

+1

完美,有了這個想法,現在我的Rspec測試finnaly去了綠色! – danslz

0

你能做到完全一樣,你做的事:

module MyModule 
    def speak(name) 
    puts "#{self} the String says hello to #{name}" 
    end 
end 

class String 
    include MyModule 
end 

"Joe".speak("danslz") 



--output:-- 
Joe the String says hello to danslz 

I`ve被要求做一些功能,

模塊是組織功能的好方法。

除了沒有必要發送一個字符串作爲參數的

當然,除非該方法以一個字符串作爲參數,例如字符串#新,字符串#[],字符串#< = >等,等等。

相關問題