2014-10-27 51 views
0

我從mashable.com拉取一個哈希值,我需要計算作者名稱的實例(作者是關鍵字,值是作者姓名)。 mashable's api計算一個值在哈希中重複的次數

{ 
new: [ 
{ 
    other_keys: 'other_values'... 
    author: 'Author's Name' 
} 
] 

我想遍歷散列,拉出作者的名字,再算上它是從混搭API的整個列表重複倍。

這是我的;它將哈希變成一個數組,迭代它,將計數添加到每個作者名稱作爲關鍵字,然後將重複數作爲值添加。

這會很好,但我無法從mashable中將它恢復到原始散列,以添加所有我想顯示的其他散列項。

all_authors = [] 

all_stories.each do |story| 
    authors = story['author'] 
    all_authors << authors 
end 

counts = Hash.new(0) 

all_authors.each do |name| 
    counts[name] += 1 
end 

counts.each do |key, val| 
    puts "#{key}: " "#{val}" 
end 

那請問什麼是應該,但我試圖把它放回原來的哈希來自Mashable:

all_stories.each do |com| 
    plorf = com['comments_count'].to_i 
    if plorf < 1 
     all_stories.each do |story| 
      puts "Title:\n" 
      puts story['title'] 
      puts "URL:\n" 
      puts story['short_url'] 
      puts "Total Shares:\n" 
      puts story['shares']['total'] 
     end 
    end 
    end 

當我到重複刪除代碼後面,它所做的一切是迭代初始的,每次輸入後,我都會得到所有作者的列表以及他們編寫的故事的數量,而不是列出每個與每個故事其他信息相關的作者以及他們編寫的故事的數量。

任何幫助,非常感謝。

回答

0

@Michael Kohl這是一個很好的答案,我想我問的是錯誤的問題。彼時我這樣做:

author = story['author'] 
puts "Number of stories by #{story['author']}: #{author_count['author']}" 

在我的「all_stories」環......

是啊,我敢肯定,我試圖「重新注入」的價值觀,以原來的亂碼,這是方式錯了...

非常感謝您的幫助,雖然

1

下面是一個簡化版本:

h = { a: 1, b: 2, c: 1, d: 1 } 
h.count { |_, v| v == 1 } #=> 3 
h.values.count(1)   #=> 3 

另外,您還可以通過按鍵和組再算上:

h.group_by(&:last).map { |v, a| [v, a.count] }.to_h #=> {1=>3, 2=>1} 

這組哈希其值,計數數組中的時代元素的鍵/值對。下面是一個更明確的版本:

grouped = h.group_by(&:last) #=> {1=>[[:a, 1], [:c, 1], [:d, 1]], 2=>[[:b, 2]]} 
    grouped.map { |v, a| [v, a.count] #=> [[1, 3], [2, 1]] 

然後最終to_h滿2個元件陣列的陣列轉換爲哈希。

+0

我需要輸入值,我比較每個關鍵,我想比較嗎? – 2014-10-27 05:35:43

+0

@DavidJohnson這是否回答了您的問題? – 2014-10-28 09:57:04

+0

我在下面回答 – 2014-10-30 17:52:50