A method defines one or more expressions to be run when the method is invoked. Your long
scripts can be shorted by extracting out repetitive expressions into a method. A script
with methods tends to be more readable than one without. Use the keyword
def to define
a method and
end to close the definition.
def hello puts "hello, world!" end
If your Ruby file only contains this code, then there will be no output when you run the code because the method is never invoked. Invoke a method be using the name of the method elsewhere in the program.
2.5.3 :001 > def hello 2.5.3 :002?> puts "hello, world!" 2.5.3 :003?> end => :hello 2.5.3 :004 > hello hello, world! => nil 2.5.3 :005 > hello hello, world! => nil 2.5.3 :006 >
Define a method with any number of parameters to accept arguments that alter the output. As an aside, you should note the difference between a “parameter” and an “argument”. Think of “parameter” as the definition or blueprint while “argument” is the actual value used at runtime. Saying, “the wrong number of parameters” and “the wrong number of arguments” would make a programmer look at different parts of their code to find the source of the problem.
2.5.3 :007 > def hello(name) 2.5.3 :008?> puts "hello, " + name + "!" 2.5.3 :009?> end => :hello 2.5.3 :010 > hello ArgumentError: wrong number of arguments (given 0, expected 1) from (irb):7:in `hello' from (irb):10 from /Users/scottserok/.rvm/rubies/ruby-2.5.3/bin/irb:11:in `<main>' 2.5.3 :011 > hello("Scott") hello, Scott! => nil 2.5.3 :012 > hello "Scott" hello, Scott! => nil
The parameter to our method acts like a variable that only our method has access to once invoked. This is more commonly referred to as a local variable because the scope (where it can be used) of the variable is limited to the block of code it is defined in. Consider this example of trying to access a local variable that is out of scope.
(irb) > def squared(y) (irb) > x = y * y (irb) > puts x (irb) > end (irb) > squared(5) 25 => nil (irb)> puts x NameError: undefined local variable or method `x' for main:Object from (irb):13 from /Users/scottserok/.rvm/rubies/ruby-2.5.3/bin/irb:11:in `<main>'