What are two uses of the splat operator?
What are two uses of the splat operator?
The splat operator, denoted as *
in Ruby and Python (and similarly used in other programming languages), serves several versatile functions in programming. Here are two primary uses of the splat operator:
The splat operator is commonly used to unpack arguments passed to functions. This allows a function to accept any number of arguments without specifying them individually in the function definition.
In Ruby:
For example, in Ruby, the splat operator can be used when calling a function to spread out the elements of an array across the function's parameters. If a function is defined to take multiple arguments, you can pass an array, and the splat operator will unpack each element of the array into a separate argument.
def sum(a, b, c)
a + b + c
end
numbers = [1, 2, 3]
sum(*numbers) # This will unpack the array into three arguments: 1, 2, and 3
In Python:
Similarly, in Python, the splat operator (*
) is used to unpack iterables into arguments expected by a function:
def describe_pet(animal, name, age):
print(f"I have a {animal}, named {name}. It is {age} years old.")
pet_details = ["dog", "WoofBox", 5]
describe_pet(*pet_details) # Unpacks the list into three separate arguments
Another common use of the splat operator is to collect multiple arguments into a single parameter. This is particularly useful when you do not know beforehand how many arguments will be passed to your function....
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào