Methods in Ruby Language
Ruby is a versatile and dynamic programming language known for its elegant and expressive syntax. One of the ke
y components that make Ruby so powerful is its robust system of methods. Methods in Ruby are similar to functions in other programming languages, but they come with a few unique features and capabilities. In this post, we will explore the concept of methods in Ruby with examples to illustrate their usage.Defining a Method
In Ruby, you can define a method using the def
keyword followed by the method name. Here’s a simple example of a method that greets a person by name:
def greet(name)
puts "Hello, #{name}!"
end
# Calling the method
greet("John") # Output: Hello, John!
In the example above, the greet
method takes a single argument name
and uses it to greet the person.
Method Arguments
Ruby methods can accept zero or more arguments. You can define default values for arguments to make them optional. Let’s see an example with a method that calculates the sum of two numbers:
def add(a, b = 0)
a + b
end
# Calling the method
result = add(3, 5)
puts result # Output: 8
result = add(3)
puts result # Output: 3
In this example, the add
method takes two arguments, but the second argument b
has a default value of 0. This allows you to call the method with just one argument if needed.
Return Values
In Ruby, methods automatically return the value of the last expression evaluated. However, you can explicitly use the return
keyword to specify a return value. Here’s an example:
def multiply(a, b)
return a * b
end
result = multiply(4, 6)
puts result # Output: 24
The return
statement is optional; if you don’t use it, the method will return the value of the last expression.
Method Chaining
Ruby is well-known for its support of method chaining, allowing you to call multiple methods in sequence. This is made possible by designing methods to return an object that can have other methods called on it. Here’s an example using a hypothetical Person
class:
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "Hi, I'm #{name} and I'm #{age} years old."
end
end
# Method chaining example
person = Person.new("Alice", 30)
person.introduce.upcase!
# Output: HI, I'M ALICE AND I'M 30 YEARS OLD.
In this example, the introduce
method returns a string, which allows us to call the upcase!
method immediately.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.