我正在开发一些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好了更新了我的答案,希望这有助于。 –
嗨,谢谢你!其实,你的建议帮助很大,我能够在我的代码中前进:) –