Skip to content

Instantly share code, notes, and snippets.

@jvans1
Last active August 29, 2015 13:57
Show Gist options
  • Save jvans1/9798262 to your computer and use it in GitHub Desktop.
Save jvans1/9798262 to your computer and use it in GitHub Desktop.
def mode(array)
#Hash.new is good here because the 0 is default for blank values
hash = Hash.new(0)
#Just use an array literal
max = []
array.each {|x| hash[x] += 1 }
hash.select do |key, value|
#i wouldn't name block local variables the same as other locals it can get confusing
hash[key].to_i == array[x].to_i
hash.values
end
end
def mode(array)
hash = Hash.new(0)
grouped_hash = array.
reduce(hash) do |hash, value|
hash[value] += 1
hash
end
max_occurence = grouped_hash.values.max
grouped_hash.select{ |k, v| v == max_occurence }.keys
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment