2014-11-23 32 views
1

我正在研究一個ruby挑戰,要求我創建一個輸入字符串數組並將字符串分隔成3個類別作爲符號返回的方法。這些符號將返回一個數組。Ruby:將數組解析爲類別,返回符號

  • 如果字符串包含單詞「貓」,則返回符號 :cat

  • 如果「狗」,則返回:dog.

  • 如果字符串不包含「狗」或「貓」則返回符號 :none

到目前爲止,我有下面的代碼,但無法通過。

def pets (house) 
    if house.include?/(?i:cat)/ 
    :cat = house 
    elsif house.include?/(?i:dog)/ 
    :dog = house 
    else 
    :none = house 
    end 
end 

input = [ "We have a dog", "Cat running around!", "All dOgS bark", "Nothing to see here", nil ]

它應該返回[ :dog, :cat, :dog, :none, :none ]

回答

1

我很驚訝,沒有人去爲case/when方法,所以在這裏它是:

def pets(house) 
    house.map do |item| 
    case item 
     when /dog/i 
     :dog 
     when /cat/i 
     :cat 
     else 
     :none 
    end 
    end 
end 

map並不複雜:你使用它時,你有ň數組元素,你想變成另一個數組n元素。

我懷疑人們不會使用case/when,因爲他們不記得語法,但它是專爲這種情況設計的,當你測試一個項目對多個選擇。它比if/elsif/elsif語法更加簡潔,恕我直言。

+0

這真的很好,效率非常高。謝謝託德! – shroy 2014-11-28 23:56:23

+0

不客氣!很高興它對你有效。 – 2014-11-29 00:01:18

1
def pets (house) 
    results = [] 
    house.each do |str| 
    if str.to_s.downcase.include?('dog') 
     results << :dog 
    elsif str.to_s.downcase.include?('cat') 
     results << :cat 
    else 
     results << :none 
    end 
    end 
    return results 
end 

這工作。這裏是上面的代碼,用僞代碼(純英文,遵循類似代碼的思考過程)編寫,所以你可以看到我是如何得到上述解決方案的。

def pets (house) 
    # Define an empty array of results 
    # 
    # Now, loop over every element in the array 
    # that was passed in as a parameter: 
    # 
    # If that element contains 'dog', 
    #  Then add :dog to the results array. 
    # If that element contains 'cat' 
    #  Then add :cat to the results array 
    # Otherwise, 
    #  Add :none to the results array 
    #   
    # Finally, return the array of results. 
end 

有你似乎是在沒有相當紮實幾個概念 - 我不認爲我能在合理的長度內有效地在這裏解釋它們。如果可能的話,試着看看你是否能遇到一位有經驗的程序員面對面地解決這個問題 - 這將比試圖自己解決問題要容易得多。

+0

制定出十分感謝! – shroy 2014-11-23 22:01:31

+0

另一個使用'map'方法的答案,實際上是一種更習慣於使用ruby的方法。不過,我認爲地圖方法的理解更加複雜,需要了解更多的編程概念。所以,我保持簡單。 – 2014-11-23 22:04:21

1

這是一個使用Array#map方法的解決方案。

def pets (house) 
    house.map do |animal| 
     if animal.to_s.downcase.include?('cat') 
      :cat 
     elsif animal.to_s.downcase.include?('dog') 
      :dog 
     else 
      :none 
     end 
    end 
end 
0

你可以使用的匹配鑰匙,和結果值的散列,具體如下:

ma = [ :cat, :dog ] 
input = [ "We have a dog", "Cat running around!", "All dOgS bark", "Nothing to see here", nil ] 
input.map {|s| ma.reduce(:none) {|result,m| s.to_s =~ /#{m}/i && m || result } } 
# => [:dog, :cat, :dog, :none, :none]