Last active
August 29, 2015 14:25
-
-
Save peterjacobson/e9c058a4b6be030351ef to your computer and use it in GitHub Desktop.
iterating through collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mode(num_list) | |
new_array = [] | |
freq = num_list.inject(Hash.new(0)) { |h,v| h[v] += 1; h} | |
# can you tell me what 'h' or 'v' means? I just got it from stackoverflow maybe you can chane it to a value that is easy to understand | |
#-----------PETE: ---------------- | |
#easiest way to check what's going on is to print everything you don't understand: | |
puts num_list | |
num_list.inject(Hash.new(0)) { |h,v| puts "#{h}, #{v}" } | |
# with arrays you want to grab each element as you iterate, i.e | |
# array.each { |element| do stuff... } | |
# with hashes, each hash entry is comprised of a key and a value - you'll likely want both, i.e | |
# hash.each { |key, value| do stuff... } | |
# in your example 'h' is the key, 'v' is the value. bad naming IMHO, 'h' is normally 'k' for key. | |
#-----------/PETE: ---------------- | |
result = num_list.max_by{ |v| freq[v] }, num_list.max_by{ |v| freq[v] }.next | |
# I need help on refactoring this | |
#-----------PETE: ---------------- | |
# that is one long line. can you break it out into variables on multiple lines? i.e | |
# very_descriptively_named_variable = num_list.max_by{ |v| freq[v] } | |
# second_very_descriptive_variable_name = num_list.max_by{ |v| freq[v] }.next | |
# result = very_descriptively_named_variable, second_very_descriptive_variable_name | |
# this should reveal your intention, and further refactoring will be easier from here. | |
#-----------/PETE: ---------------- | |
puts freq | |
puts result.inspect | |
#so I can see whats happening | |
end | |
num_list = [1,1,2,2,3,3,3,3,4,4,4,4,5] | |
puts mode(num_list) | |
#just for checking |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment