Ruby Methods Flashcards Preview

Ruby - Launch School - Introduction to Programming > Ruby Methods > Flashcards

Flashcards in Ruby Methods Deck (6):
1

method

a procedure of code. define it with def. End it with end.

def say
# method body goes here
end

2

parameter

Parameters are used when you have data outside of a method's scope, but you need access to it within the method's scope. If the method does not need access to any outside data, you do not need to define any parameters. Below "(words)" is the parameter.

def say(words)
puts words
end

say("hello")
say("hi")
say("how are you")
say("I'm fine")

3

arguments

Arguments are pieces of information that are sent to a method to be modified or used to return a specific result. We "pass" arguments to a method when we call it. Here, we are using an argument to pass the word, or string of words, that we want to use in the say method. When we pass those words into the method, they're assigned to the variable words and we can use them how we please from within the method. Note that the words variable is scoped at the method level; that is, you cannot reference this variable outside of the say method.

4

default parameters

When you're defining methods you may want to structure your method so that it always works, whether given parameters or not.

def say(words='hello')
puts words + '.'
end

say()
say("hi")

5

return

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it.

6

puts

returns nil

def add_three(n)
puts n + 3
end

add_three(5)
8
=> nil