Step 21: Creating Methods


So Ruby has a lot of cool and useful methods, but what if we want to create our own? Creating methods is a huge proportion of what you’ll be doing as you continue learning how to program. Let’s see how to do this in Ruby:

def capitalize_join(arr)
    arr.join(" ").capitalize
end


sentence = capitalize_join(["see", "you", "soon"])
puts(sentence)

In Ruby, we create methods with the def keyword and the name of the method on the first line, the code for what the method should do next, and finally an end keyword. We can also define arguments that should be passed in, as we did above, where our capitalize_join method is expecting one argument to be passed in. Multiple arguments can be defined with commas. We can also use methods we defined earlier in other methods.

Also, notice that defining and using a method are two different things. We defined our style="color: red;">capitalize_join method on line 1, but in order to make it do anything we still had to call it later.

def shuffled_letters(str)
    str.split("").shuffle  
end


def combined_shuffled_letters(str1, str2, str3)
    shuffled_letters(str1) + shuffled_letters(str2) + shuffled_letters(str3)
end

combined_shuffled_letters("Cat", "Dog", "Human")

Did you pick up on what happens when we add arrays together?