In Ruby, methods and functions are very similar, and the terms are often used interchangeably. Both refer to a block of code that can be called by its name and can optionally take arguments and return a value. Here are some examples of defining and calling methods/functions in Ruby:
.jpg)
Defining a method:
def say_hello(name) puts "Hello, #{name}!" end
Calling a method:
say_hello("Alice") # Output: "Hello, Alice!"
Defining a function:
def add_numbers(a, b) return a + b end
Calling a function:
result = add_numbers(2, 3) puts result # Output: 5
In Ruby, methods/functions can have default argument values, variable-length argument lists, and blocks. Here are some examples:
Method with default argument values:
def say_hello(name="World") puts "Hello, #{name}!" end say_hello() # Output: "Hello, World!" say_hello("Alice") # Output: "Hello, Alice!"
Method with variable-length argument list:
def sum(*numbers) total = 0 numbers.each do |n| total += n end return total end puts sum(1, 2, 3, 4, 5) # Output: 15
Method with block:
def map(array) result = [] array.each do |element| result << yield(element) end return result end numbers = [1, 2, 3, 4, 5] squares = map(numbers) {|n| n * n} puts squares.inspect # Output: [1, 4, 9, 16, 25]
In this example, the map method takes an array and a block as arguments. The block is executed for each element of the array, and the result is stored in a new array that is returned by the method. The yield keyword is used to call the block and pass in the current element as an argument.
These are just a few examples of the many ways to define and call methods/functions in Ruby.
In Ruby, you can define your own methods to perform specific tasks or operations. Here's an example of how to define a method:
def add_numbers(num1, num2) sum = num1 + num2 return sum end
In this example, we've defined a method called add_numbers that takes two arguments num1 and num2. Inside the method, we've assigned the sum of num1 and num2 to a variable called sum. Finally, we've returned the value of sum using the return keyword.
To call the add_numbers method, you would pass in two arguments:
result = add_numbers(5, 10) puts result
In this example, we're calling the add_numbers method with num1 equal to 5 and num2 equal to 10. The result variable will be assigned the value returned by the add_numbers method, which is the sum of num1 and num2. We're then printing the value of result to the console using the puts method.
You can also define methods that don't take any arguments:
def say_hello puts "Hello, world!" end ``
0 Comments