2017-11-11 10 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 

私が欲しい結果の配列は次のとおりです。

曲の名前は、例えば、各要素の中間のテキストです

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>' 
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"] 

しかし、私は次のエラーを取得しています

私は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)あなたは、ソートのブロックで1つの文字列を返すされており、それは確かに整数

2)を返す整数

3)を必要とする、

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

ようですが、これはより良い

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

Read the docssortの方法

+0

あなたの神..ありがとう:) –

+0

私の喜びサー; – Ursus

関連する問題