Skip to content

Instantly share code, notes, and snippets.

@chellberg
Created May 1, 2015 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chellberg/730a4046b94c40d8e453 to your computer and use it in GitHub Desktop.
Save chellberg/730a4046b94c40d8e453 to your computer and use it in GitHub Desktop.
indyrb interview problem
def counted_recurring_elements_in(array)
counts_by_number = array.inject({}) do |memo, element|
memo[element] = memo[element].to_i + 1 # I like this trick but I wish it didn't rely on knowing nil.to_i == 1
memo
end
recurring_counts_by_number = counts_by_number.select do |number, count|
count > 1
end
recurring_counts_by_number
end
@jonstorer
Copy link

nil.to_i == 0*

@scotwk
Copy link

scotwk commented May 10, 2015

I believe this does the same thing while removing the hack you don't like.

counts_by_number = array.inject(Hash.new(0)) do |memo, element|
    memo[element] += 1
    memo
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment