Methods Flashcards
What does method invocation mean?
Calling a method
What is the role of default parameter in a method definition?
It is executed/printed if the caller doesn’t send any arguments
Why cannot local variables within a method definition be referenced from outside of the method definition?
Because a method definition creates its own scope outside the regular scope of execution.
What does a method do?
It allows you to extract the common code to one place
How do you define a method?
def name_of_the_method () #method body comes here end
What is the only way to permanently alter arguments
passed in to method definitions?
Perform an action on the argument to mutate the caller
e.g. methods like:
.pop (removes last element of an array and returns it)
Is the “return” keyword necessary to return something from a method?
No. It’s feature of Ruby.
However, if you put it in the middle of a method definition, it returns that line’s value without executing the rest.
e.g. def add_three(num) return num + 3 num + 4 end
returned_value = add_three(6)
puts returned_value
It returns 9
How can chaining methods break down easily? Tell an example!
If it gets a “nil” along the chain.
e.g.
def add_three(n)
puts n + 3
end
add_three(5).times {puts “there’s an issue”}
=>It crashes because when add_three(5) is evaluated, 8 is output and “nil” is returned and assigned to .times, making it crash
What is the result of the following:
def add(a, b)
a + b
end
def substract(a, b)
a - b
end
def multiply(a,b)
a * b
end
substract(add(add(54,23), multiply(3,2)), substract(9, 2))
76
What is the difference between “p” and “puts” methods?
Both evaluate what you pass to them (and print it), BUT “p” returns what you pass to it, while “puts” always returns nil
e.g.
p “hello”
hello
=> “hello”
puts “hello”
hello
=>nil
What does the following code print and why?
def number if true num = 4 else 3 end end
puts number
It prints 1.
Variable assignment still returns the value it was assigned to.
It works the same way as if the assignment was not even there, because we don’t use the assignment anywhere else.
What do you use Enumerable#reduce for?
It combines all elements of the given array by applying a binary operation. It is specified by a block or symbol. e.g. (symbol version) def average(nums) sum = nums.reduce(:+) sum / nums.count end
we added the elements of the array together and determined their average.
What do you use Enumerable#count for?
It returns the number of items in enum (or array I guess)
if an argument is given, it counts only those.
e.g.
arr = [1,2,2,3,6]
arr.count(2)
=>2