2016-07-05 28 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

嘿,非常感謝!實際上,這是一個非常好的來源。 –