在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
我需要更改第三行,以选择倒数第二个附件,而不是最后一个附件
3条答案
按热度按时间ztyzrc3y1#
是这样吗
wribegjk2#
如果你使用Rails,你可以使用
Array#second_to_last
方法:这只是Sergio为
[-2]
提出的ActiveSupport语法糖你也可以在纯Ruby中使用这个方法。只需在代码中包含这部分库:
mpbci0fu3#
在@WesleyBond发布之前,我计划使用的一件事也是如此: