Skip to content

Instantly share code, notes, and snippets.

@eric
Created December 21, 2011 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eric/1508079 to your computer and use it in GitHub Desktop.
Save eric/1508079 to your computer and use it in GitHub Desktop.
module ObjectDiagnostics
extend self
def display(method, options = {})
res = format(method, options)
res.each { |l| puts l }
end
def format(method, options = {})
res = calculate(method, options)
case method
when :array_by_content
res.map! { |k, count| "#{count}: #{k.inspect[0..50]}"}
when :string_by_content
res.map! { |k, count| "#{count}: #{k[0..50].inspect}"}
else
res.map! { |k, count| "#{count}: #{k}" }
end
res
end
def calculate(method, options = {})
h = Hash.new { |h,k| h[k] = 0 }
mod = Object
p = case method
when :class_by_count
proc { |obj| h[obj.class.to_s] += 1 rescue nil }
when :array_by_length
mod = Array
proc { |obj| h[obj.length] += 1 }
when :array_by_content
mod = Array
proc { |obj| h[obj] += 1 rescue nil }
when :string_by_length
mod = String
proc { |obj| h[obj.length] += 1 }
when :string_by_content
mod = String
proc { |obj| h[obj] += 1 }
else
raise "Unknown method: #{method}"
end
ObjectSpace.each_object(mod, &p)
res = h.sort_by { |(k, v)| v }
if top = options[:top]
res = res[-top ... -1]
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment