在Ruby中,有没有一种简单的方法来选择倒数第二个项目?

pexxcrt2  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(110)

在Ruby中,有没有一种简单的方法来选择倒数第二个项目?类似于css中的nth-child选择器?
下面是我的代码:

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

我需要更改第三行,以选择倒数第二个附件,而不是最后一个附件

ztyzrc3y

ztyzrc3y1#

result = card.attachments[-2].url

是这样吗

wribegjk

wribegjk2#

如果你使用Rails,你可以使用Array#second_to_last方法:

card.attachments.second_to_last

这只是Sergio为[-2]提出的ActiveSupport语法糖
你也可以在纯Ruby中使用这个方法。只需在代码中包含这部分库:

require 'active_support/core_ext/array/access'
mpbci0fu

mpbci0fu3#

在@WesleyBond发布之前,我计划使用的一件事也是如此:

card.attachments&.reverse[1].url

相关问题