2017-11-11 113 views
0

我想要的歌曲以下數組排序:紅寶石:字符串零的比較失敗(參數錯誤)

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 

問題:

  1. 爲什麼會出現這個錯誤?
  2. 應該做些什麼來擺脫錯誤?
  3. 你能否建議一種更好的方法來根據元素的特定部分對數組進行排序?就像在這種情況下,字符串元素的子字符串?

回答

2

1)要返回在排序的塊中的一個字符串,它需要一定的整數

2)返回一個整數

3),像

array.sort { |a, b| a.split(" - ")[1] <=> b.split(" - ")[1] } 

但這更好

array.sort_by { |item| item.split(" - ")[1] } 

Read the docssort方法

+0

你的天神.. thanksss :) –

+0

我的榮幸爵士;) – Ursus