【问题标题】:Split array. Ruby拆分数组。红宝石
【发布时间】:2014-01-05 02:37:14
【问题描述】:

你能帮我解决一些问题吗? 我有这样的数据库数组

 str = Hiring::Tag.all
  Hiring::Tag Load (0.1ms)  SELECT `hiring_tags`.* FROM `hiring_tags`
=> [#<Hiring::Tag id: 1, name: "tag1", created_at: "2013-12-10 11:44:39", updated_at: "2013-12-10 11:44:39">,
    #<Hiring::Tag id: 2, name: "tag2", created_at: nil, updated_at: nil>,
    #<Hiring::Tag id: 3, name: "tag3", created_at: nil, updated_at: nil>,
    #<Hiring::Tag id: 4, name: "wtf", created_at: "2013-12-11 07:53:04", updated_at: "2013-12-11 07:53:04">,
    #<Hiring::Tag id: 5, name: "new_tag", created_at: "2013-12-11 10:35:48", updated_at: "2013-12-11 10:35:48">]

我需要像这样拆分这个数组:

    data:[{id:1,name:'tag1'},{id:2,name:'tag2'},
          {id:3,name:'tag3'},{id:4,name:'wtf'},{id:5,name:'new_tag'}] 

请帮帮我!

【问题讨论】:

标签: ruby arrays split


【解决方案1】:

如果您使用 ActiveRecord 4.0

Hiring::Tag.pluck(:id, :name).map{ |id, name| {id: id, name: name} }

【讨论】:

    【解决方案2】:

    一种可能的解决方案:

    Hiring::Tag.all.map {|h| {id: h.id, name: h.name} }
    

    the documentation for map

    【讨论】:

      【解决方案3】:

      你可以试试下面的代码。

      Hiring::Tag.all.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }
      

      Hiring::Tag.all.map { |f| [f.name.to_sym, f.value] }]
      

      【讨论】:

        猜你喜欢
        • 2019-12-24
        • 1970-01-01
        • 2012-09-13
        • 2016-06-28
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 2019-08-09
        • 1970-01-01
        相关资源
        最近更新 更多