2016-07-05 145 views
1

我正在开发一些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'] 

回答

1

你可以使用Enumerable#map这里:

my_pets.map{ |s| s.gsub(/a/,'@') } 
#=> ["Buddy the [email protected]@", "Coco the [email protected]", "[email protected] the [email protected]@keet"] 

您的代码几乎工程,只是删除puts arrayif声明。然后只需调用该函数。

#Use CamelCase for class names NOT snake_case. 
#Using two spaces for indentation is sensible. 
class CoolPets 
    def a_replace(array) 
    array.each do |string| 
     string.gsub!(/a/, "@") 
    end 
    end 
end 

cool = CoolPets.new 
my_pets = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet'] 
p cool.a_replace(my_pets) 
#=> ["Buddy the [email protected]@", "Coco the [email protected]", "[email protected] the [email protected]@keet"] 
+0

嘿,感谢您的建议。然而,我问的原因是我特别想知道是否可以将my_pets数组重新分配给Cool_Pets类(以及这种方法是否可行)。对此有何建议? –

+0

@Leia_Organa好了更新了我的答案,希望这有助于。 –

+0

嗨,谢谢你!其实,你的建议帮助很大,我能够在我的代码中前进:) –

0

不知道这是你在寻找什么,但检查出混入http://ruby-doc.com/docs/ProgrammingRuby/html/tut_modules.html#S2

module CoolPet 
    def a_replace(array) 
    array.each do |string| 
     if string.include?("a") 
     string.gsub!(/a/, "@") 
     end 
    end 

    puts array.inspect 
    end 
end 

class MyPet 
    include CoolPet 
end 

array = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet'] 
pet = MyPet.new 
pet.a_replace(array) # => ["Buddy the [email protected]@", "Coco the [email protected]", "[email protected] the [email protected]@keet"] 
+1

嘿,非常感谢!实际上,这是一个非常好的来源。 –

相关问题