< Language Tutorials

Methods are Scratch's custom blocks, but in Ruby. As someone who is reading this tutorial probably knows, one can create a custom block in Scratch by clicking the "Make a Block" button in the Scratch editor and creating the block, then adding scripts onto the Define () block.
The Make a Block button.
In Ruby, this is the syntax for making a method:
def name_of_method(parameter, parameter, etc.)
  # Code
end

One can execute a method in your code by doing name_of_method(filled_in_parameter, filled_in_parameter, etc.). So, if one was going to make a method that printed "My favorite animal is a" and then their favorite animal (and then a period) to the console, they could do this:

# Defining the method, hence "def"
def my_favorite_animal(animal)
  puts "My favorite animal is a " + animal + "."
end

# Executing the method
my_favorite_animal("dog")

That code would print My favorite animal is a dog. to the console.

What it looks like when one has clicked "Make a Block" and is now making a custom block in Scratch.
If the person who made this method wanted to make the method more robust and do more things, they could add even more parameters and code to the method.
# Defining the method, hence "def"
def my_favorite_animal(animal, pattern)
  puts "My favorite animal is a " + animal + "."
  puts "I especially like #{pattern} #{animal}s." # One can use the "#{}" syntax to add something to strings. "gets" takes what the user typed, and "chomp" removes the space made by the user pressing enter after they typed what they typed.
  puts "What is your favorite animal?"
  users_favorite_animal = gets.chomp # gets.chomp takes input from the user through the console. It's kind of like the "ask" block in Scratch.
  puts "I also like #{users_favorite_animal}s. In fact, they are my second favorite animal!"
end

# Executing the method
my_favorite_animal("dog", "spotted")

What that code would do is print to the console My favorite animal is a dog., then I especially like spotted dogs., then What is your favorite animal? After that the user would be able to type their favorite animal. It would change the value of the users_favorite_animal variable to what the user typed, and print I also like (whatever the user typed)s. In fact, they are my second favorite animal!