Skip to content

Instantly share code, notes, and snippets.

@Andsbf
Created March 4, 2015 20:30
Show Gist options
  • Save Andsbf/071873dcbc264433cfda to your computer and use it in GitHub Desktop.
Save Andsbf/071873dcbc264433cfda to your computer and use it in GitHub Desktop.
Debug Exercise
require 'pry'
list = {'yvr' => 'Vancouver', 'yba' => 'Banff', 'yyz' => 'Toronto', 'yxx' => 'Abbotsford', 'ybw' => 'Calgary'}
binding.pry
# Why is it returning nil instead of first element of the list above
p list.first
require 'pry'
def average(numbers=nil)
# binding.pry
return nil if ( numbers == nil || numbers == [] )
sum = 0
divisor = numbers.size
numbers.each do |num|
# binding.pry
sum += num.to_f
divisor -= 1 if num == nil
end
sum / divisor
end
## TEST HELPER METHOD
def test_average(array = nil)
print "avg of #{array.inspect}:"
result = average(array)
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
# binding.pry
# Non-existent set should return nil
test_average() # => nil
# BONUS: Should ignore nils in the set
test_average([9,6,nil,3]) # => 6
require 'pry'
def sum(list)
total = 0
list.each do |ele|
total += ele
end
total
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?
require 'pry'
def char_count(list)
@letters = Hash.new(0)
list.each do |word|
# binding.pry
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 method1
method2
end
def method2
method3
end
def method3(a=nil)
puts a
end
method1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment