2015-02-09 63 views
0

在計算ruby字數的邏輯時遇到一些麻煩。我的目標是傳入一些文本,並獲得數組中定義的某個類別的單詞的總數。所以,如果我給下面的變量,我想找出有什麼水果提到的詞的分數:通過數組遍歷數組(另一個Ruby字數)

content = "I went to the store today, and I bought apples, eggs, bananas, 
yogurt, bacon, spices, milk, oranges, and a pineapple. I also had a fruit 
smoothie and picked up some replacement Apple earbuds." 

fruit = ["apple", "banana", "fruit", "kiwi", "orange", "pear", "pineapple", "watermelon"] 

(我知道複數/奇異的是不相符的;只是一個例子)。這是我一直在試圖代碼:

content.strip 
contentarray = content.downcase.split(/[^a-zA-Z]/) 
contentarray.delete("") 
total_wordcount = contentarray.size 

IRB測試:

contentarray.grep("and") 
=> ["and", "and", "and"] 
contentarray.grep("and").count 
=> 3 

於是我嘗試:

fruit.each do |i| 
    contentarray.grep(i).count 
end 
=> ["apple", "banana", "fruit", "kiwi", "orange", "pear", "pineapple", "watermelon"] 

它只是返回數組,沒有計數。如果它返回任何數字,我會將它們全部添加。我們的目標是要結束了:

fruitwordcount 
=> 6/33 

=> .1818181 

我試着搜索,發現有很多的方法說的內容數組轉換成散列計數出現許多教程做的,但是當我只需要一個子集的計數時,就會給出每個單詞的計數。我似乎無法找到通過字符串數組搜索數組或字符串的好方法。我發現一些文章說要使用來自Multiset gem的直方圖,但這仍然給每一個字。任何幫助將非常感激;請原諒我的nberbery。

回答

0

您正在查找的方法是map而不是eacheach爲數組中的每個元素執行塊,然後返回原始數組。 map創建一個包含塊返回值的新數組。

fruit.map do |i| 
    contentarray.grep(i).count 
end 
=> [1, 0, 1, 0, 0, 0, 1, 0] 
+0

作品就像一個冠軍。謝謝! – Rootski 2015-02-09 11:02:50

+0

不客氣。您現在可以[接受答案](http://stackoverflow.com/help/someone-answers),您認爲這是解決問題的最佳方案。 – cbliard 2015-02-10 08:09:18

1

Fruit#each只是重複的水果,而你可能想收集價值。 map就派上用場了:

result = fruit.map do |i| 
    [i, contentarray.grep(i).count] 
end 

無論您需要的fruit ⇒ count哈希,它很簡單:

result = Hash[result] 

希望它能幫助。

0

這是因爲each方法只是迭代和執行該塊。使用mapcollect來執行該塊並返回一個數組。

result = fruit.map { |i| counterarray.grep(i).count } 
0

array#每個返回數組本身as per ruby docs

你可能想嘗試給一些其他方法一試。特別是countmap看好:

fruit.map do |f| 
    contentarray.count{|content| content == f} 
end 
0

得到公正的水果讓你的陣列 - contentarray.keep_if{|x| fruit.include?(x) }然後把它變成一個哈希計數你發現教程做的方式。

或者只是使用在contentarray注入構建hash

contentarray.inject(Hash.new(0)) do |result, element| 
    if fruit.include?(element) 
    result[element] += 1 
    end 
    result 
end 

Hash.new(0)設置默認值設置爲0,所以我們只需要添加一個