To understand methods a little better, let’s jump into writing one ourselves. Here’s a very simple method you can write yourself that merely puts information to the screen. You can write a method inside IRB without creating a new file.
In your terminal type irb:
$ irb # type irb to open the ruby interpreter irb(main):001:0> def hello irb(main):002:1> puts "Hello World!" irb(main):003:1> end => nil
In Ruby, we define a method using the
def keyword. The next word after def is the name of our method. This would be our hello method, which takes no arguments (kind of like your parents at bedtime). We’ll explain arguments in a moment.
Like at the end of a movie or bedtime story, the word
end in Ruby means the same thing as it does to you--that this is the end of our method. Any code in between our def and end keywords will be run by the computer for this particular method. This code is our "block" we give the method to execute.
To run our method, we simply call its name
hello by typing it into the terminal prompt.
irb(main):004:0> hello Hello World! => nil
In order to write and save several methods, it will be easier to create a file and run the code inside the file, so let’s do that. Exit the terminal by typing