Methods, Blocks & Sorting Flashcards
method
a reusable section of code written to execute a certain task.
defined using “def”
i.e.
def greeting
puts “hello”
end
greeting
-> hello
three parts to a method
- def & name of the method
- body: describes the procedure of the methos
- end
parameter
placeholder for the method argument
argument
the argument you use in running a method
splat argument
a method that can receive one or more arguments.
use * to signal to an parameter that it can receive several arguments
i.e.
def what_up(greeting, *friends)
return
returns back a value from a method
blocks
nameless methods.
define by either do and end
or { }
difference between methods and blocks
methods can be called several times whereas blocks can only be called once
.sort!
Sorts values in an array either numerically or alphabetically
my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2]
puts my_array.sort!
prints out
[1, 2, 3, 4, 5, 6, 7, 8, 9]
<=>
combines comparison operator.
compares to objects
It returns 0 if the first operand (item to be compared) equals the second, 1 if the first operand is greater than the second, and -1 if the first operand is less than the second.
i.e.
book_1 = “A Wrinkle in Time”
book_2 = “A Brief History of Time”
book_1 <=> book_2
returns 1
.reverse!
reverse sorts and array from last to first