arraysrubyobjectruby-hash

Is there a simple way to select the second to last item in Ruby?


Is there a simple way to select the second to last item in Ruby? Something similar to like the nth-child selector in css?

Here is my code:

def pic2
    @pic2 ||= begin
      result = card.attachments&.last&.url # I need this to be changed to select the second to last attachment instead of the last
      if result
        logger_card("Pic found on trello card (#{result})")
        result
      else
        logger_card('No Trello Picture')
        nil
      end
    end
  end

I need that third line changed to select the second to last attachment instead of the last


Solution

  • result = card.attachments[-2].url
    

    Something like that?