【问题标题】:Sorting a hash using a method from the corresponding model使用相应模型中的方法对哈希进行排序
【发布时间】:2014-11-13 04:59:21
【问题描述】:

假设您有一个模型 Dog,其属性为“年龄”,这是一种确定“吠叫频率”的方法:

class Dog < ActiveRecord::Base
  scope by_age, -> { order('age ASC') }

  def barking_frequency
    # some code
  end
end

在您的控制器中,您有:

def index
  @dogs = Dog.by_age
end

一旦有了@dogs 的哈希值,如何按 barking_frequency 对其进行排序,以便结果将特定年龄的狗排序在一起,如下所示:

Name    Age   Barking Frequency
Molly    2    1
Buster   2    4
Jackie   2    7
Dirk     3    1
Hank     3    3
Jake     3    4
Spot     10   0

【问题讨论】:

    标签: ruby-on-rails ruby sorting hash


    【解决方案1】:

    以下将起作用:

    def index
      @dogs = Dog.by_age.sort_by { |dog| [dog.age, dog.barking_frequency] }
    end
    

    【讨论】:

    • 那不是很漂亮吗?
    • @PatriceGahide 是什么意思? ;)
    • 抱歉,我仍然对 Ruby 代码有时多么美丽和简单感到震惊,我只是在写我的想法;)
    • @PatriceGahide 感谢您的赞赏.. :-)
    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2015-01-01
    • 2015-10-23
    • 2012-05-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多