计算Ruby中值的出现次数

时间:2015-06-10 16:44:36

标签: ruby

我正在尝试计算mysql表列中不同值的数量。可能值的范围是整数,范围是0-10。以下代码正在运行,但我想知道是否有更优雅的方法来执行此操作?

# Example data from Mysql
result = [{ :column1 => "2", :column2 => "3", :column3 => "1"},{ :column1 => "2", :column2 => "3", :column3 => "1"},{ :column1 => "1", :column2 => "2", :column3 => "3"}]

# Init hash
final_result = Hash.new { |h, k| h[k] = {  } }

# Loop result columns
result.each do |single_column|

    # Loop single items inside columns
    single_column.each do |single_result|

            # Create column if does not exist
            if final_result[single_result[0]][single_result[1]].nil? then
                final_result[single_result[0]][single_result[1]] = 1
            else
                final_result[single_result[0]][single_result[1]] += 1
            end
    end
end

puts final_result
# => {:column1=>{"2"=>2, "1"=>1}, :column2=>{"3"=>2, "2"=>1}, :column3=>{"1"=>2, "3"=>1}}

2 个答案:

答案 0 :(得分:1)

这里有一些清理空间。最明显的部分是长而笨重的nil?陈述。测试vs false是没有意义的,请记住在Ruby中逻辑上错误的东西是nilfalse,因为nil永远不会要显示在此处,可以删除针对Hash.new的测试。

不仅如此,您还可以使用自定义result = [ { :column1 => "2", :column2 => "3", :column3 => "1"}, { :column1 => "2", :column2 => "3", :column3 => "1"}, { :column1 => "1", :column2 => "2", :column3 => "3"} ] # Init hash final_result = Hash.new { |h, k| h[k] = Hash.new(0) } # Loop result columns result.each do |single_column| single_column.each do |r| final_result[r[0]][r[1]] += 1 end end puts final_result.inspect 电话进入正确的轨道,但是您还远远不够。为什么不用零初始化第二层?

这导致代码看起来像:

    $select = $conn_pdo->query('SELECT * FROM foo');
    $meta = $select->getColumnMeta(0);
    echo "Name of table: ".$meta['table'];

答案 1 :(得分:1)

查看有效记录// background thread Realm realm = null; try { realm = Realm.getDefaultInstance(); final List<Contact> contacts = getContacts(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.insertOrUpdate(contacts); realm.where(Contact.class) .equalTo(ContactFields.IS_BEING_SAVED, false) // compile 'dk.ilios:realmfieldnameshelper:1.1.0' .findAll() .deleteAllFromRealm(); // delete all non-saved data // in your case, this is where you'd handle the cascading too though manually for(Contact realmContact : realm.where(Contact.class).findAll()) { // realm 0.89.0+ realmContact.setIsBeingSaved(false); // reset all save state } } }); } finally { if(realm != null) { realm.close(); } } 方法(doc link)。您可以将其与count结合使用来完成您要实现的目标。

group