Methods Flashcards

Information about methods

You may prefer our related Brainscape-certified flashcards:
1
Q

How do you allow for multiple, but unknown number of arguments in a method.

A
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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
What does the " * " SPLAT operator do in the following?
def whats_up(greeting, *names) 
    names.each do |name|
    puts "#{greeting},"#{name} 
  end
end
A

It allows for unknown number of arguments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s the different between ‘print “String”’ and ‘return “String”’

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
What's the return/output value of this code? Why?
def add(num1, num2)
    return num1 + num2
   "hello" 
end

add(4, 5)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How are destructive methods usually denoted?

A

With an exclamation mark. “!”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the following code do/return?

fruits = [“orange”, “apple”, “banana”, “pear”, “grapes”]
fruits.sort! do |first,second|
second <=> first
end

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you sort this array in descending order?

fruits = [“orange”, “apple”, “banana”, “pear”, “grapes”]

A

fruits.sort! do |first,second|
second <=> first
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly