我正在尝试对以下歌曲数组进行排序:
array = ["Jurassic 5 - What's Golden - hip-hop",
"Action Bronson - Larry Csonka - indie",
"Real Estate - Green Aisles - country",
"Real Estate - It's Real - hip-hop",
"Thundercat - For Love I Come - dance"]
我想要的是根据歌曲的名称对数组进行排序。歌曲的名称是每个元素的中间文本,例如:
array = ["Jurassic 5 - **What's Golden** - hip-hop"]
我尝试使用以下代码执行此操作:
array.sort do |a, b|
a = a.split(" - ")
b = b.split(" - ")
a[1] <=> b[1]
a = a.join(" - ")
b = b.join(" - ")
end
我想要的结果数组是:
array = ["Thundercat - For Love I Come - dance",
"Real Estate - Green Aisles - country",
"Real Estate - It's Real - hip-hop",
"Action Bronson - Larry Csonka - indie",
"Jurassic 5 - What's Golden - hip-hop"]
但是我收到以下错误:
ArgumentError: comparison of String with 0 failed
from (irb):52:in `>'
from (irb):52:in `sort'
from (irb):52
from C:/Ruby23/bin/irb.cmd:19:in `<main>'
我检查了要在PRY中比较的值,两者都是字符串。
pry(#<MusicLibraryController>)> a.class
=> Array
pry(#<MusicLibraryController>)> a[1].class
=> String
pry(#<MusicLibraryController>)> b.class
=>Array
pry(#<MusicLibraryController>)> b[1].class
=> String
问题:
答案 0 :(得分:2)
1)你在sort的块中返回一个字符串,它需要一个整数
2)返回一个整数
3)确定,如
array.sort { |a, b| a.split(" - ")[1] <=> b.split(" - ")[1] }
但这更好
array.sort_by { |item| item.split(" - ")[1] }
sort
方法的