【问题标题】:jRuby / Rails is it possible to get unique items from a Hash and group only the unique ones together?jRuby / Rails是否可以从哈希中获取唯一项目并将唯一的项目组合在一起?
【发布时间】:2012-01-18 06:42:10
【问题描述】:

是否可以获得哈希的唯一值?假设我有一个散列,其中一个键是“名称”名称可以出现几十次,但它只会说它本身的 10 个变体都是唯一的。我想要做的是能够获取这 10 个独特的名称并基于它们构建一个视图。但为了正确展开视图,我需要知道那些唯一的名称。我想我必须建立一个数组,或者另一个散列或者一些独特的名字。因此,如果原始哈希具有匹配项,我可以使用“每个”遍历该数组,然后将每个唯一元素应用于该部分或视图上的块。希望这对某人有意义。谁能帮帮我。

val = {
    :status => "successful",
    :service_list => [
        {
            :service_name => "oozie",
            :status => "RUNNING",
            :status_message => "Running Master Service",
            :host => "1"
        },
        {
            :service_name => "single-namenode",
            :status => "RUNNING",
            :status_message => "Running Service",
            :host => "1"
        },
        {
            :service_name => "single-database",
            :status => "RUNNING",
            :status_message => "Running Service",
            :host => "1"
        }
]}

我正在使用的哈希的截断版本。

【问题讨论】:

    标签: ruby-on-rails hash jruby


    【解决方案1】:

    不确定它是否是正确的答案,但是可以像这样获得唯一服务名称的列表:

    val[:service_list].map { |service| service[:service_name] }.uniq
    # ["oozie", "single-namenode", "single-database"]
    

    更新

    对按 service_name 分组的服务的哈希进行迭代要容易一些,下面是一个示例:

    在控制器的操作中:

    @services =  val[:service_list].group_by { |service| service[:service_name] }
    
    # {
    #    "oozie" => [ { ... }, { ... } ],
    #    "single-namenode" => [ { ... }, { ... } ],
    #    "single-database" => [ { ... }, { ... } ]
    # }
    

    在你看来

    <% for name, services in @services %>
        All services with name <%= name %>
        <% for service in services %>
            <%= service[:host] %>, Status: <%= service[:status] %>
        <% end %>
    <% end %>
    

    希望有帮助

    【讨论】:

    • 我认为这是我在概念上绝对想要的。我对 Rails 比较陌生,所以我不确定在确定唯一的之后如何迭代每一个我试过 服务:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2011-02-15
    相关资源
    最近更新 更多