Câu hỏi phỏng vấn Ruby
Câu hỏi

What are two uses of the splat operator?

Câu trả lời

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:

1. Argument Unpacking in Functions

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.

ruby Copy
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:

python Copy
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

2. Collecting Arguments into a List or Array

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

junior

Gợi ý câu hỏi phỏng vấn

entry

What can you say about an identifier that begins with a capital letter?

middle

What is the difference between #== and #equal? ?

junior

What is a module? Can you tell me the difference between classes and modules?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào