根据字符串的最后一个单词对数组进行排序

时间:2017-12-27 15:06:52

标签: ruby string sorting

我有一个像:

这样的数组
[
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650497/img_0_0_0.jpg",
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650510/img_0_0_20.jpg",
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650499/img_0_0_10.jpg",
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650521/img_0_0_30.jpg", 
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650498/img_0_0_1.jpg",
 "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650522/img_0_0_31.jpg"
]

我想根据"/"之后字符串的最后一个单词对其进行排序,这是"img_0_0"单词。但我找不到任何解决办法。

5 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

array.sort_by do |item| 
  item.match(/\/img_(\d)+_(\d+)_(\d+).jpg$/).captures.map(&:to_i)
end

Demonstration

答案 1 :(得分:2)

按字母顺序排序:

> puts urls.sort_by { |u| u.split('/').last }
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650497/img_0_0_10.jpg
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650510/img_0_0_2.jpg
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650499/img_0_1_1.jpg

按数字“自然地”订购:

> puts urls.sort_by { |u| u.split('/').last.scan(/\d+/).map(&:to_i) }
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650510/img_0_0_2.jpg
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650497/img_0_0_10.jpg
https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650499/img_0_1_1.jpg

答案 2 :(得分:1)

我假设您希望项目按数字顺序排序,以便img_0_0_9位于img_0_0_10之前。为此,我们提取所有项目的img部分的后缀,将它们转换为数值并相应地对数组进行排序:

arr.sort_by { |e| e[%r|(?<=/img_0_0_).*(?=\.jpg\z)|].to_i }

#⇒ [
#   [0] "https://ya.../img_0_0_0.jpg",
#   [1] "https://ya.../img_0_0_1.jpg",
#   [2] "https://ya.../img_0_0_10.jpg",
#   [3] "https://ya.../img_0_0_20.jpg",
#   [4] "https://ya.../img_0_0_30.jpg",
#   [5] "https://ya.../img_0_0_31.jpg"
# ]

答案 3 :(得分:1)

另一种可能的解决方案

arr.sort{ |x, y| x.split('/')[-1].gsub('.jpg', '') <=> y.split('/')[-1].gsub('.jpg', '') }

答案 4 :(得分:1)

links = [
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650497/img_0_0_0.jpg",
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650510/img_0_0_20.jpg",
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650499/img_0_0_10.jpg",
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650521/img_0_0_30.jpg",
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650498/img_0_0_1.jpg",
  "https://yallamotor-development-assets.s3.ap-south-1.amazonaws.com/2650522/img_0_0_31.jpg"]

links.sort_by do |link|
  link.last(12)
      .split('')
      .map {|x| Integer(x) rescue nil }
      .compact
      .join
      .to_i
end

这将从每个数组中获取最后12个字符并获取每个数字,将其转换为整数,然后对其进行排序