2011-08-09 66 views
0

我正在研究一個腳本,它收集來自我的數據庫的所有註釋並將它們插入到散列中。我然後做一個收集有關意見Hash和分裂的意見分成兩個獨立的評論哈希(vid_comments & wall_comments)Ruby:使用數組

w_hash["comments"] << contender.profile.comments.where("created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)") 
    w_hash["comments"].delete_if { |x| x.blank? } 
    w_hash["vid_comments"], w_hash["wall_comments"] = [], [] 

    w_hash["comments"].each do |c| 
     if !c.media_id.nil? 
     w_hash["vid_comments"] << c 
     elsif c.parent_id == 0 
     w_hash["wall_comments"] << c 
     end 
    end 

反正是有縮短的代碼?我對Ruby很新(PHP導入),所以請原諒我對我可能做錯的事情的無知。

編輯:添加代碼位來自@Mchl(下)..

+1

考慮將您的問題移至http://codereview.stackexchange.com。 – maerics

+0

謝謝!後移到codereview:http://codereview.stackexchange.com/questions/3987/ruby-working-with-arrays – dennismonsewicz

回答

1

一種方式我看到的(即最近的PHP導入自己)是改變這一點:

w_hash["vid_comments"] = w_hash["comments"].collect { |c| !c.media_id.nil? } 
w_hash["wall_comments"] = w_hash["comments"].collect { |w| w.parent_id == 0 } 

進入

w_hash["comments"].each do |c| 
    if !c.media_id.nil? 
    w_hash["vid_comments"] << c 
    elsif c.parent_id == 0 
    w_hash["wall_comments"] << c 
    end 
end 
+0

謝謝!我最近被介紹給Ruby中的'.collect'方法,並且一直試圖在DRY(ing)我的代碼中變得更好!謝謝您的幫助! – dennismonsewicz

+0

可能有一種方法可以在一條簡單而優雅的線條中完成所有工作,但我還沒有完成; P – Mchl

+0

我要麼:P我最終修改了一下代碼......我粘貼了新的 – dennismonsewicz