1

Say I have an array, and I use the keep_if or select methods to delete everything but one object for the array -- is there a way to take that object out of the array, so it's not an array any more?

For example, the way my models are set up, previous and current will only ever have one object.

 def more_or_less?(project, current_day)
    words = project.words
    current = words.select {|w| w.wrote_on == current_day}
    previous = words.select {|w| w.wrote_on == (current_day - 1.day)}
 end

So, if I want to do a comparison, like if current.quantity > previous.quantity -- I've resorted to actually writing if current.last.quantity > previous.last.quantity but I'm assuming there's a more idiomatic way?

2 Answers 2

2

If you're deleting all but one entries, why not use find to choose the one thing you care about? Something like this:

def more_or_less?(project, current_day)
  words    = project.words
  current  = words.find { |w| w.wrote_on == current_day }
  previous = words.find { |w| w.wrote_on == (current_day - 1.day) }
  if current.quantity > previous.quantity
    #...
  end
end

If you're in ActiveRecord land, then you can use detect as derp says or to_a to get a plain array that you can use find on:

def more_or_less?(project, current_day)
  words    = project.words
  current  = words.detect    { |w| w.wrote_on == current_day }
  previous = words.to_a.find { |w| w.wrote_on == (current_day - 1.day) }
  if current.quantity > previous.quantity
    #...
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

No, that's what I was looking for. Why didn't occur to me that find would work, I don't know.
Actually -- I'm in a Rails project, so when I use find it's looking for a primary key.
What is words then? Is it a single ActiveRecord object?
words is an array (project has_many => :words), that's why I'm selecting out of it in the first place.
1

detect is an alias for find, maybe that would work

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.