0
  @open  = Array.new
  @close = Array.new
  @posts.each do |post|
     if !post.status.nil? and post.status == 'Open'
        @open.push(post)
     else
        @close.push(post)
     end
  end

Can i write it in less verbose way ?

4 Answers 4

9

Sounds like a job for partition:

partition { |obj| block } → [ true_array, false_array ]
partition → an_enumerator

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

This should do the job:

@open, @closed = @posts.partition { |p| p.status == 'Open' }
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. How long you are in Ruby/Rails ? :-)
Humm.. I am closely 2 years in Ruby. Still crawling.. :-(
1

Another idea:

@open = @post.select{ |post| post.status == 'Open'}
@close = @post.reject{ |post| post.status == 'Open'}

1 Comment

You could replace your second line with @close = @post - @open.
0

You dont have to check nil explicity. Something like this will do.

@posts.each { |post| post.status == 'Open' ? @open.push post : @close.push }

1 Comment

@HunterMcMillen you got a point in there. You may need the nil check depending on your data.
0

Just to help you write code that's more Ruby-like, here's how I'd write your original code:

open_ary  = []
close_ary = []
@posts.each do |post|
  if post.status && post.status == 'Open'
    open_ary << post
  else
    close_ary << post
  end
end

It could be written more concisely, and would remove a couple lines, but it'd lose readability, which is always something to consider. That said, @muistooshort's answer is really the best way to do it because it relies on the partition method which was created for this sort of use-case.

Comments

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.