Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rwpr/336b7767b894eb65993d to your computer and use it in GitHub Desktop.
Save rwpr/336b7767b894eb65993d to your computer and use it in GitHub Desktop.
#Run the code. Read the error message.
#Change the assigned value of sample_avg so that it does not throw an error.
def mean(numbers)
sum = numbers.inject(:+)
return sum / numbers.length
end
# This will throw an error. Change this line so that it works.
sample_avg = mean([5, 3, 6, 10])
#comment out the above code with your new solution
#in order to pass the method of mean, the parameter has to be an array. this change is made above to dismiss the error.
def mean(*numbers)
sum = numbers.inject(:+)
return sum / numbers.length
end
#Instead of changing the method invocation, change the definition.
#In other words, rewrite the method so that it can take any number of arguments.
sample_avg = mean(5, 3, 6, 10)
#comment out the above code with your new solution
#using splat allows us to define unlimited amount of arguments on the method
#Ruby is a dynamically typed programming language, which means that you do not have to define the type of a variable when you assign it.
#Most of the time, this is a very Good Thing. Rubyists can use duck typing, which is a form of dynamic typing.
#In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself.
#Source: Wikipedia
#Sometimes, though, the objects our program receives are of a different type than the ones we expected it to receive. This is called a TypeError, and you will see them all over the place in Ruby programs. So get used to it.
#The goal of the code below is to produce an output string and a sorted array from an array input. There is at least one error in #this code. You must find it. You must fix it.
#def print_and_sort(array)
# output_string = []
# array.each do |element|
# element = element.to_s
# output_string << element
# end
# array = output_string
# p array.sort
#end
#words = %w{ all i can say is that my life is pretty plain }
#words_with_nil = words.dup.insert(3, nil)
#mixed_array = ["2", 1, "5", 4, "3"]
#print_and_sort(words)
#print_and_sort(words_with_nil)
#print_and_sort(mixed_array)
#comment out the above code with your new solution
def print_and_sort(array)
output_string = ""
array.compact!
array.map!(&:to_s)
p array.sort
end
words = %w{ all i can say is that my life is pretty plain }
words_with_nil = words.dup.insert(3, nil)
mixed_array = ["2", 1, "5", 4, "3"]
print_and_sort(words)
print_and_sort(words_with_nil)
print_and_sort(mixed_array)
#comment out the above code with your new solution
#delete the nil from the array
#then map all the elements in the array and change them into strings
#sort the array and print them out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment