尝试对Ruby数组进行排序时获取“NoMethodError”

时间:2017-01-17 18:50:28

标签: arrays ruby sorting field

我正在使用Ruby 2.4。我很难根据存储在该数组中的对象的特定字段对数组进行排序。我有

    results.sort! { |a,b| 
      puts "a time: #{a.time_in_ms} b time: #{b.time_in_ms}" 
      a.time_in_ms < b.time_in_ms
    }

虽然我已经验证我的rails控制台中的两个字段都是整数,但是当我运行此代码时出现“”错误...

a time: 16968700 b time: 21784000 
NoMethodError: undefined method `>' for true:TrueClass
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:668:in `sort'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:668:in `populate_overall_rank_info'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:408:in `get_data_hash'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:25:in `get_race_times'
    from /Users/davea/Documents/workspace/myproject/app/services/active_com_service.rb:57:in `process_page_data'
    from /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:88:in `process_race_data'
    from (irb):2
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console.rb:65:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console_helper.rb:9:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

如何根据对象中的字段进行排序?

2 个答案:

答案 0 :(得分:1)

试试这个

 results.sort_by! { |element| element.time_in_ms }

答案 1 :(得分:1)

尝试其中一个

results.sort_by(&:time_in_ms)

长篇

results.sort { |a, b| a.time_in_ms <=> b.time_in_ms }

sort方法期望块返回整数值而不是布尔值。你得到这个错误,因为你的块返回一个布尔值。

引用ri文档

  

返回一个数组,其中包含enum排序的项目,可以根据自己的<=>方法,也可以使用提供的块的结果。该块应返回-10+1,具体取决于a和b之间的比较。