0

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)..

2

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!! I have recently been introduced to the .collect method in Ruby and have been trying to get better at DRY(ing) up my code! Thanks for the help!
There's probably a way to do it all in one simple and elegant line, but I'm not there yet ;P
Me either :P I ended up modifying your code slightly... I pasted the new above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.