【发布时间】:2017-11-11 01:13:21
【问题描述】:
我正在尝试对以下歌曲数组进行排序:
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
问题:
- 为什么会出现此错误?
- 应该怎么做才能消除错误?
- 能否建议一种更好的方法来根据元素的特定部分对数组进行排序?就像在这种情况下字符串元素的子字符串一样?
【问题讨论】:
标签: arrays ruby sorting comparison