【问题标题】:Ruby: Comparison of String to zero failed (Argument Error)Ruby:字符串与零的比较失败(参数错误)
【发布时间】: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

问题:

  1. 为什么会出现此错误?
  2. 应该怎么做才能消除错误?
  3. 能否建议一种更好的方法来根据元素的特定部分对数组进行排序?就像在这种情况下字符串元素的子字符串一样?

【问题讨论】:

    标签: arrays ruby sorting comparison


    【解决方案1】:

    1) 您在排序块中返回一个字符串,它需要一个整数

    2) 返回一个整数

    3) 当然,喜欢

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

    不过这样更好

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

    Read the docs 用于 sort 方法

    【讨论】:

    • 我的荣幸先生;)
    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多