Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. def mode(num_list)
  2. new_array = []
  3.  
  4. freq = num_list.inject(Hash.new(0)) { |h,v| h[v] += 1; h}
  5. # 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
  6.  
  7. #-----------PETE: ----------------
  8.  
  9. #easiest way to check what's going on is to print everything you don't understand:
  10.  
  11. puts num_list
  12. num_list.inject(Hash.new(0)) { |h,v| puts "#{h}, #{v}" }
  13.  
  14. # with arrays you want to grab each element as you iterate, i.e
  15. # array.each { |element| do stuff... }
  16. # with hashes, each hash entry is comprised of a key and a value - you'll likely want both, i.e
  17. # hash.each { |key, value| do stuff... }
  18. # in your example 'h' is the key, 'v' is the value. bad naming IMHO, 'h' is normally 'k' for key.
  19.  
  20. #-----------/PETE: ----------------
  21.  
  22. result = num_list.max_by{ |v| freq[v] }, num_list.max_by{ |v| freq[v] }.next
  23. # I need help on refactoring this
  24.  
  25. #-----------PETE: ----------------
  26.  
  27. # that is one long line. can you break it out into variables on multiple lines? i.e
  28.  
  29. # very_descriptively_named_variable = num_list.max_by{ |v| freq[v] }
  30. # second_very_descriptive_variable_name = num_list.max_by{ |v| freq[v] }.next
  31. # result = very_descriptively_named_variable, second_very_descriptive_variable_name
  32.  
  33. # this should reveal your intention, and further refactoring will be easier from here.
  34.  
  35. #-----------/PETE: ----------------
  36.  
  37. puts freq
  38. puts result.inspect
  39. #so I can see whats happening
  40.  
  41. end
  42.  
  43. num_list = [1,1,2,2,3,3,3,3,4,4,4,4,5]
  44. puts mode(num_list)
  45. #just for checking
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement