Skip to content

Instantly share code, notes, and snippets.

@FioFiyo
Created March 31, 2016 01:05
Show Gist options
  • Save FioFiyo/64d963017b67134bad9af8861d03ef79 to your computer and use it in GitHub Desktop.
Save FioFiyo/64d963017b67134bad9af8861d03ef79 to your computer and use it in GitHub Desktop.
Debugging
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]
def average(numbers)
#check if nil or empty first before running the block
if numbers.nil? || numbers.empty?
nil
else
sum = 0
numbers.compact!
numbers.each do |num|
sum += num.to_i.to_f
end #ends do
sum / numbers.size
end #ends if
end #ends method
## TEST HELPER METHOD
def test_average(array = nil)
print "avg of #{array.inspect}:"
# remove all nils before passing on the array
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
def sum(list)
list.each do |ele|
sum = 0
sum += ele
end
sum
end
def newsum(list)
list.inject{ |sum, n| sum + n}
print
end
list1 = [16,21,31,42,55]
# 1. The following should return 165 instead of an error
puts newsum(list1)
# 2. How would you refactor it using an enumerable method other than each? Examples of enumerables: map, select, inject, reject, detect.
def char_count(list)
# ANOTHER WAY, shorter code => letters = Hash.new(0)
letters = {}
list.each do |word|
word.split('').each { |letter| letters[letter] += 1 }
end
letters
end
def char_count2(list)
# create a hash
letters = {}
# loop through the list
list.each do |word|
#split list to get characters in strings and in a variable to loop again
word_in = word.split('')
word_in.each do |letter|
#put the characters(letter) into the has LETTERS and
#if the hash contains the character(letter) give a
#value of +1, otherwise assign the letter a value of 1 as it's
#the first instance
if letters[letter]
letters[letter] += 1
else
letters[letter] = 1
end
end
end
#o Output letters otherwise only the WORD comes out
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_count2(['apples', 'oranges', 'hipsters', 'are', 'same'])
puts char_count(['apples', 'oranges', 'hipsters', 'are', 'same'])
# 2. What are the improvements you can do to above code?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment