Count the occurence of values in Ruby -
i'm trying count numbers of different values in mysql table columns. range of possible values integer , 0-10. following code working, i'm wondering if there more elegant way this?
# example data 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 |single_column| # loop single items inside columns single_column.each |single_result| # create column if not exist if final_result[single_result[0]][single_result[1]].nil? 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}}
there's room cleaning here. obvious part long, clunky if
statement. test vs nil?
pointless, remember in ruby only things logically false false
, nil
, since false
never going show here, test vs. nil
can removed.
more that, though, you're on right track custom hash.new
call, don't go far enough. why not initialize second tier zero?
that results in code looks like:
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 |single_column| single_column.each |r| final_result[r[0]][r[1]] += 1 end end puts final_result.inspect
Comments
Post a Comment