【问题标题】:Ruby - Splititng Array after getting data from MysqlRuby - 从 Mysql 获取数据后拆分数组
【发布时间】:2013-03-27 05:24:42
【问题描述】:

我有以下代码可以将 MySQL 数据库中的数据提取到我的 rails 控制器中

@main = $connection.execute("SELECT * FROM builds WHERE platform_type IS NOT NULL")

这会返回一个 mysql2 类型的对象,我猜它的行为类似于数组。

我想将其拆分为 2 个数组,第一个数组的 platform_type 为“TOTAL”,其他数组中的所有内容。

【问题讨论】:

    标签: ruby-on-rails ruby arrays ruby-on-rails-3


    【解决方案1】:

    它实际上返回一个Mysql2::Result 对象。当然可以

    totals = []
    others = []
    main.each { |r|
      (r['platform_type'] == 'TOTAL' ? totals : others) << r
    }
    

    但是为什么不使用 Rails 方式呢:

    Builds.where("platform_type = ?", 'TOTAL')
    Builds.where("platform_type NOT IN ?", [nil, 'TOTAL'])
    

    【讨论】:

    • #<:result:0xb73e9790> 的未定义方法 `each_hash'
    • @sagarvikani 哎呀,对不起,在Mysql2 中,该方法被称为each 而不是each_hash。我的错。
    【解决方案2】:

    试试 array.select。类似的东西

    total = @main.select { |build| build.platform_type == 'TOTAL' }
    not_total = @main.reject { |build| build.platform_type == 'TOTAL' }
    

    http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/

    更好的是,按照这个答案使用 Enumerable.partition:Ruby Select and Reject in one method

    【讨论】:

    • 嗯……Mysql::Result 实际上不是Array 的后代。
    猜你喜欢
    • 2015-01-24
    • 2023-01-19
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多