Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. ##BUG 1
  2.  
  3. list = {'yvr' => 'Vancouver', 'yba' => 'Banff', 'yyz' => 'Toronto', 'yxx' => 'Abbotsford', 'ybw' => 'Calgary'}
  4.  
  5.  
  6.  
  7. p list ['yvr']
  8. #2 p list.first
  9.  
  10. ##BUG 2
  11.  
  12. def average(numbers)
  13. sum = 0
  14. numbers.each do |num|
  15. sum += num.to_i
  16. end
  17. sum / numbers.size.to_f unless numbers.empty?
  18. end
  19.  
  20. ## TEST HELPER METHOD
  21. def test_average(array=[])
  22. print "avg of #{array.inspect}:"
  23. result = average(array.compact)
  24. puts result
  25. end
  26.  
  27. ## TEST CODE
  28. test_average([4,5,6]) # => 5
  29. test_average([15,5,10]) # => 10
  30.  
  31. # Should treat string like number
  32. test_average([15,'5',10]) # => 10
  33.  
  34. # Should show decimal value
  35. test_average([10, 5]) # => 7.5 instead of just 7
  36.  
  37. # Watch out! Even tests can have bugs!
  38. test_average([9, 5, 7])
  39.  
  40. # Empty set should return nil, not throw an error
  41. test_average([]) # => nil
  42.  
  43. # Non-existent set should return nil
  44. test_average() # => nil
  45.  
  46. # BONUS: Should ignore nils in the set
  47. test_average([9,6,nil,3]) # => 6
  48.  
  49.  
  50. ##BUG3
  51.  
  52. #lsdef sum(list)
  53. # list.each do |ele|
  54. # sum = 0
  55. # sum += ele
  56. # end
  57. # sum
  58. #end
  59. #
  60. #list1 = [16,21,31,42,55]
  61. #
  62. ## 1. The following should return 165 instead of an error
  63. #puts sum(list1)
  64. #
  65. ## 2. How would you refactor it using a Ruby list method?
  66. #
  67.  
  68. ##1
  69.  
  70. def bug(array)
  71. sum = 0
  72. array.each do |ele|
  73. sum += ele
  74. end
  75. sum
  76. end
  77.  
  78.  
  79. list1 = [16,21,31,42,55]
  80. puts bug(list1)
  81.  
  82. ##2
  83.  
  84. list1.reduce :+
  85.  
  86. ##BUG 4
  87.  
  88. #def char_count(list)
  89. # @letters = {}
  90. # list.each do |word|
  91. # word.split('').each { |letter| @letters[letter] += 1 }
  92. # end
  93. # @letters
  94. #end#
  95. # Why the long face(error)?
  96. # 1. This should return count of each letter in the list
  97.  
  98. #puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
  99.  
  100.  
  101. # 2. What are the improvements you can do to above code?
  102.  
  103.  
  104.  
  105. def char_count(list)
  106. @letters = {}
  107. list.each do |word|
  108. word.split('').each do |letter|
  109. @letters[letter].nil? ? @letters[letter] = 1 : @letters[letter] += 1
  110. end
  111. end
  112. @letters
  113. end
  114.  
  115. puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement