Methods Flashcards
parameter
used when you have data outside of a method definition’s scope, but you need access to it within the method definition. If the method definition does not need access to any outside data, I do not need to define any parameters.
argument
piece of information that is sent to a method invocation to be modified or used to return a specific result. We “pass” arguments to a method when we call it.
Note that the words local variable is ______ at the method definition level; that is you cannot reference this local variable outside of the say method definiton
scoped
default parameter
def say(words=’hello’)
puts words + ‘.’
end
say() say("hi") say("how are you") say("I'm fine") Notice that say() prints hello. to the console.
method invocation with a block
Method invocation with a block
[1, 2, 3].each do |num|
puts num
end
mutating the caller
sometimes, when calling a method, the argument can be altered permanently
Method definition
Method definition
def print_num(num)
puts num
end
Two ways to call methods:
- The some_method(obj) is when you send arguments to a method call.
- Methods called with an explicit caller, like this a_caller.some_method(obj). Best to think of this as some_method modifying a_caller.
string.upcase method
changes every lowercase letter to uppercase
string.downcase method
change every uppercase letter to lowercase
string.swapcase
switches the case of every letter in the string
string.capitalize
switches the first character to uppercase (if it’s a letter)
string.center
adds spaces to the beginning and end of the string to make it centered.
string. ljust
string. rjust
similar to center, but they pad the string with spaces on the right and left sides