DEV Community

Shay
Shay

Posted on • Edited on

Ruby: Methods & Functions

In two years of my learning, I have delved into JavaScript first, Python second, and now it is Ruby's time to shine. With all of the programming languages that I have been studying, I know that they all share commonalities between each other.

First, they all have methods! Makes sense because the point of a programming language like Ruby, Python, and JavaScript are that they create dynamic functionality to applications.

What are Methods?

In Ruby, methods are the building blocks of code organization and functionality. They are essentially named blocks of code that perform specific tasks and can return values. Think of them as mini-programs within your larger program. Here's a breakdown of what methods are all about in Ruby:

The next section will provide a common list of methods that are used in codes. While this list is small, there is a wide range of methods that can be used for Ruby.

Method Examples

.length = Check the amount of chars, letters, etc.

.reverse = Reverses the value

.upcase / .downcase = Converts string to all uppercase or lowercase

Def Method

The def method is used when a premade method is not useful to your code and you need to make a part of it more specific to completing a task. Def is short for define where you're defining a name for the method that you're creating.

Then, you'll add the function. More methods can be applied inside your created method!

At the end, ensure to end the code with the end keyword, so that the program will know where to end the function and proceed to the next line of code.

Example

def calculate_area(length, width)
  length * width
end
Enter fullscreen mode Exit fullscreen mode
def is_even?(number)
  number % 2 == 0
end
Enter fullscreen mode Exit fullscreen mode
def greet_all(names)
  names.each { |name| greet(name) }
end
Enter fullscreen mode Exit fullscreen mode

Ready to dive deeper? Check out these resources for even more method madness:

Ruby Documentation: https://www.ruby-lang.org/en/
Rails Guides: https://guides.rubyonrails.org/
Learn to Code With Ruby: https://teamtreehouse.com/library/topic:ruby

Happy coding!

theGlamTechie

Top comments (0)