« Back to Index

Is there a more elegant way in Ruby to filter data from an object and store it in another object. We’re searching for a key (which can appear multiple times) and I only want to store the key once, but to also increment that key’s value every time the key is found.

View original Gist on GitHub

object to object filtering.rb

require 'httparty'

data = HTTParty.get('http://some_url/')

browsers = {}

data.each do |item|
  browser = item['browser']['family']

  if browsers[browser]
    browsers[browser] = browsers[browser] + 1
  else
    browsers[browser] = 1
  end

  # yes we *could* use a tertiary conditional but that can be a bit too terse sometimes
  # browsers[browser] = browsers[browser] ? browsers[browser] + 1 : 1 
  # i would argue that's actually harder to read than the expanded if/else
end

puts browsers # {"Chrome Mobile"=>3, "IE Mobile"=>2}

# Update: the following refactor from Kenoir did the trick...
browsers = data.reduce({}) do | obj, item |
  browser = item['browser']['family']
  obj[browser] = (obj[browser].nil?) ? 1 : obj[browser] + 1
  obj
end