Ruby Intro/ Methods Flashcards
What is a method?
Why are methods so convenient?
a block of code written to perform a specific task
you only have to write a method once, but it can be called from other places in your program. also, you can make just one change in your method’s code, but that one change can affect many things in your program. you can give info to a method, and the method can give you info back
“keep all that code in one place”
What’s another word for “methods?”
functions
What does a parameter do?
establishes the the type of argument you must give the method
def say_hello(name)
puts (“Hello, “ + name)
end
“a method can accept parameters as input”
Here is a method:
def my_method(name)
puts (“Hello, “ + name)
puts (“Hi, “ + name)
end
What will print to the screen? Why?
“Hi, Joe”
because ruby will return the last returnable piece of info in the code
Here is a method:
def my_method(name)
puts (“Hello, “ + name)
puts (“Hi, “ + name)
end
If you want “Hello, Joe” to print to the screen, what word can you add to the code?
def my_method(name)
return puts (“Hello, “ + name)
puts (“Hi, “ + name)
end
my_method(“Joe”
in a method, do you have to add the keyword “return?”
no, returns are automatic in ruby, but you can add “return” to your code if you want to specify a certain line to return a value
does a method always need parameters?
no. you only need parameters if your method needs access to outside data
with regard to a method, what are “arguments?”
pieces of info sent to a method to be modified or used to return a specific result
Here’s a method:
def my_method(name) puts ("Hello, " + name) puts ("Hi, " + name) end ----------
Can the local variable “name” be referenced outside of the method definition?
no
outer scope cannot see inner scope
What does a default parameter do?
it assigns a value to the local variable if the caller doesn’t pass an argument to the method
There is only one way for a local variable in a method to gain access to data outside of the method? What is it?
The data must be passed to the method in the form of an argument