我正在開發一些Ruby項目。我仍然在學習Ruby的一些基本原理,但是我需要一些幫助來解決我遇到的一個特殊問題。 我需要使用與類關聯的方法分配一些已經創建的元素。我該怎麼做呢? 這是我的例子。將類方法分配給已經建立的元素?
比方說,我有數組
my_pets = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet']
的數組,我也有,我已經寫了我需要的my_pets陣列訪問特定函數的類。基本上,這個函數循環遍歷一個字符串數組,並用「@」替換「a」。
class Cool_Pets
def a_replace(array)
array.each do |string|
if string.include?("a")
string.gsub!(/a/, "@")
end
end
puts string
end
end
有沒有辦法將my_pets指定爲Cool_Pets類的一部分,以便它可以使用a_replace方法?
這是我想要的結果:
a_replace(my_pets) = ['Buddy the [email protected]', 'Coco the [email protected]', '[email protected] the [email protected]@keet']
嘿,感謝您的建議。然而,我問的原因是我特別想知道是否可以將my_pets數組重新分配給Cool_Pets類(以及這種方法是否可行)。對此有何建議? –
@Leia_Organa好了更新了我的答案,希望這有助於。 –
嗨,謝謝你!其實,你的建議幫助很大,我能夠在我的代碼中前進:) –