Good Code

A Medium publication gathering insightful articles on good programming practices, featuring expert tips, coding best practices, software design principles, and real-world examples for developers passionate about writing clean, efficient, and maintainable code.

An image exploring the intricacies of Ruby method arguments. It features abstract representations for different argument types like required, optional, keyword, and variable-length arguments, each with distinctive shapes or patterns. Ruby-colored gemstones symbolize the Ruby language, set against a digital, code-themed background with snippets of Ruby code. The design, blending reds, pinks, and digital blues, creates a vibrant, educational look into Ruby’s argument handling.
Ruby’s Argument Versatility: Exploring Method Arguments” — A visual deep dive into the diverse and intricate world of Ruby method arguments, showcasing the language’s flexibility.

Member-only story

Exploring the Flexibility of Ruby Method Arguments: A Deep Dive

3 min readDec 20, 2023

--

Ruby, known for its elegance and flexibility, offers various ways to define method arguments, catering to different needs and scenarios. This article will guide you through the different types of arguments in Ruby, providing examples to illustrate their use and benefits.

Basic Arguments

Basic or positional arguments are defined in the order they are expected to be received. They are straightforward and commonly used in Ruby methods.

def sum_numbers(num1, num2, num3)
puts num1 + num2 + num3
end

sum_numbers(1, 2, 3)
# => 6

You can assign default values to these arguments:

def sum_numbers(num1, num2 = 2, num3 = 3)
puts num1 + num2 + num3
end

sum_numbers(1)
# => 6

Explicit Named Arguments

Keyword arguments in Ruby methods allow you to name your arguments, making the method calls more readable and self-explanatory.

def introduce_person(name:, age:)
puts "Meet #{name}, who is #{age} years old."
end
introduce_person(name: "John", age: 28)
# => Meet John, who is 28 years old.

Combining Basic and Keyword Arguments

--

--

Good Code
Good Code

Published in Good Code

A Medium publication gathering insightful articles on good programming practices, featuring expert tips, coding best practices, software design principles, and real-world examples for developers passionate about writing clean, efficient, and maintainable code.

Alessio Bussolari
Alessio Bussolari

Written by Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.

No responses yet