Methods Flashcards
Information about methods
How do you allow for multiple, but unknown number of arguments in a method.
Using the splat " * " operator. Example: def whats_up(greeting, *names) names.each do |name| puts "#{greeting},"#{name} end end
whats_up(‘Hey there’, ‘Timmy’, ‘James’, ‘Ben’)
What does the " * " SPLAT operator do in the following? def whats_up(greeting, *names) names.each do |name| puts "#{greeting},"#{name} end end
It allows for unknown number of arguments.
What’s the different between ‘print “String”’ and ‘return “String”’
RETURN stops the code and returns a value, but does not print to screen.
PRINT prints to the screen, but does not stop the code to return anything(implicit return… if last line of code).
What's the return/output value of this code? Why? def add(num1, num2) return num1 + num2 "hello" end
add(4, 5)
The return value is 9 because the return breaks out of the block and returns the value ‘num1 + num2’.
The “hello” code does not get executed because the block is exited before then.
How are destructive methods usually denoted?
With an exclamation mark. “!”
What does the following code do/return?
fruits = [“orange”, “apple”, “banana”, “pear”, “grapes”]
fruits.sort! do |first,second|
second <=> first
end
It returns the fruits array sorted in Descending Alphabetical order.
The <=> ‘combined comparison operator’ returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
How do you sort this array in descending order?
fruits = [“orange”, “apple”, “banana”, “pear”, “grapes”]
fruits.sort! do |first,second|
second <=> first
end