Skip to content

Instantly share code, notes, and snippets.

@McTano
Forked from monicao/debug01.rb
Last active May 25, 2016 19:37
Show Gist options
  • Save McTano/d7aaa4911128de2ef4e87308a65ee0c9 to your computer and use it in GitHub Desktop.
Save McTano/d7aaa4911128de2ef4e87308a65ee0c9 to your computer and use it in GitHub Desktop.
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[0] treats 0 as a key, not an integer index.
# we can call the first element like so, assuming we want the value.
#p list.values[0]
# if we want the key, we can do it like so:
# p list.keys[0]
# but, again assuming we want 'Vancouver' we should probably call
# it by the key instead:
p list['yvr']
def average(numbers=[])
sum = 0
numbers.each do |num|
sum += num.to_f
end
sum / (numbers.size - numbers.count(nil)) unless numbers.size == 0
end
## TEST HELPER METHOD
def test_average(array=[])
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]) #=> 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
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 an enumerable method other than each? Examples of enumerables: map, select, inject, reject, detect.
def sum_alt(list)
list.inject {|sum, i| sum + i}
end
puts sum_alt(list1)
def char_count(list)
letters = Hash.new(0)
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
# ex: { "a" => 4, "p" => 3, "l" => 1 ...}
puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
# A: caused an error when the letter was not already present as a key.
# 2. What are the improvements you can do to above code?
# A: added default value 0 to prevent error, which has the added benefit
# of allowing us to check the count of a letter which is not present in
# the original array and get the correct answer: 0.
def method1
method2
end
def method2
method3
end
def method3(a)
puts a
end
method1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment