开发者

Converting an array with only one object in Ruby

开发者 https://www.devze.com 2023-04-03 12:31 出处:网络
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

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?


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


detect is an alias for find, maybe that would work

0

精彩评论

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