0

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

mechnicov
  • 12,025
  • 4
  • 33
  • 56
McKay Whiting
  • 152
  • 11

3 Answers3

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

Something like that?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
thomas305
  • 82
  • 7
1

If you use Rails, you can use Array#second_to_last method:

card.attachments.second_to_last

It is just ActiveSupport syntax sugar for [-2] that Sergio proposed

You can also use this method in pure Ruby. Just include this part of library in your code:

require 'active_support/core_ext/array/access'
mechnicov
  • 12,025
  • 4
  • 33
  • 56
-2

One thing that also works that I was planning on using before @WesleyBond posted was the following:

card.attachments&.reverse[1].url
McKay Whiting
  • 152
  • 11