Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##BUG 1
- list = {'yvr' => 'Vancouver', 'yba' => 'Banff', 'yyz' => 'Toronto', 'yxx' => 'Abbotsford', 'ybw' => 'Calgary'}
- p list ['yvr']
- #2 p list.first
- ##BUG 2
- def average(numbers)
- sum = 0
- numbers.each do |num|
- sum += num.to_i
- end
- sum / numbers.size.to_f unless numbers.empty?
- end
- ## TEST HELPER METHOD
- def test_average(array=[])
- print "avg of #{array.inspect}:"
- result = average(array.compact)
- puts result
- end
- ## TEST CODE
- test_average([4,5,6]) # => 5
- test_average([15,5,10]) # => 10
- # Should treat string like number
- test_average([15,'5',10]) # => 10
- # Should show decimal value
- test_average([10, 5]) # => 7.5 instead of just 7
- # Watch out! Even tests can have bugs!
- test_average([9, 5, 7])
- # Empty set should return nil, not throw an error
- test_average([]) # => nil
- # Non-existent set should return nil
- test_average() # => nil
- # BONUS: Should ignore nils in the set
- test_average([9,6,nil,3]) # => 6
- ##BUG3
- #lsdef sum(list)
- # list.each do |ele|
- # sum = 0
- # sum += ele
- # end
- # sum
- #end
- #
- #list1 = [16,21,31,42,55]
- #
- ## 1. The following should return 165 instead of an error
- #puts sum(list1)
- #
- ## 2. How would you refactor it using a Ruby list method?
- #
- ##1
- def bug(array)
- sum = 0
- array.each do |ele|
- sum += ele
- end
- sum
- end
- list1 = [16,21,31,42,55]
- puts bug(list1)
- ##2
- list1.reduce :+
- ##BUG 4
- #def char_count(list)
- # @letters = {}
- # list.each do |word|
- # word.split('').each { |letter| @letters[letter] += 1 }
- # end
- # @letters
- #end#
- # Why the long face(error)?
- # 1. This should return count of each letter in the list
- #puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
- # 2. What are the improvements you can do to above code?
- def char_count(list)
- @letters = {}
- list.each do |word|
- word.split('').each do |letter|
- @letters[letter].nil? ? @letters[letter] = 1 : @letters[letter] += 1
- end
- end
- @letters
- end
- puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement