Skip to content

Instantly share code, notes, and snippets.

@heavymetta
Last active September 3, 2015 14:48
Show Gist options
  • Save heavymetta/7465650c1f2852d88d5d to your computer and use it in GitHub Desktop.
Save heavymetta/7465650c1f2852d88d5d to your computer and use it in GitHub Desktop.
Debugging 01.02.03.04
///// DEBUG 01 ///// --------------------
list = {'yvr' => 'Vancouver', 'yba' => 'Banff', 'yyz' => 'Toronto', 'yxx' => 'Abbotsford', 'ybw' => 'Calgary'}
# Why is it returning nil instead of first element of the list above
p list['yvr']
///// DEBUG 02 ///// -------------------
def average(numbers)
return nil if numbers.empty?
sum = 0
numbers.each do |num|
sum += num.to_f
end
average = sum / numbers.size
average % 1 == 0 ? average.round : average
end
## TEST HELPER METHOD
def test_average(array = nil)
return nil if array == nil
print "avg of #{array.inspect}:"
result = average(array)
p 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
///// DEBUG 03 ///// ----------------------
def sum(list)
sum = 0
list.each do |ele|
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 an enumerable method other than each? Examples of enumerables: map, select, inject, reject, detect.
p list1.inject(0) {|sum, i| sum + i }
p list1.inject(0, :+)
p list1.inject([]) { |acc, item| acc << item if item % 2 == 0; acc }
p list1.inject([]) { |acc, item| acc << item + 1 }
///// DEBUG 04 ///// -------------------
def char_count(list)
fruit = Hash.new(0)
list.each do |word|
word.split('').each { |letter| fruit[letter] += 1 }
end
fruit
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?
////////////////////// -------------
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment