开发者

Ruby: working with arrays

I am working on a script that collects all comments from my DB and inserts them into a hash. I then do a collect on the comments hash and split the comments into two separate comment hashes (vid_comments & wall_comments)

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

Is there anyway to shorten the code? I am pretty new to Ruby (PHP import) so excuse my ignorance in things I may be doing wrong.

EDIT: A开发者_如何学Godded in code bit from @Mchl (below)..


One way I see (being a recent PHP import myself) would be to change this:

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 }

Into

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜