dennismonsewicz
dennismonsewicz

Reputation: 25552

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: Added in code bit from @Mchl (below)..

Upvotes: 0

Views: 109

Answers (1)

Mchl
Mchl

Reputation: 62395

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

Upvotes: 1

Related Questions