0
0
Rubyprogramming~5 mins

Variable-length arguments (*args) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does *args mean in a Ruby method definition?

*args allows a method to accept any number of arguments as an array. It collects all extra arguments passed into the method.

Click to reveal answer
beginner
How do you access the individual arguments passed via *args inside the method?

You can treat args as a normal array and access elements by index, loop over it, or use array methods.

Click to reveal answer
beginner
Example: What will this method print?<br>
def greet(*names)
  names.each { |name| puts "Hello, #{name}!" }
end

greet('Alice', 'Bob')

This will print:<br>Hello, Alice!<br>Hello, Bob!

Click to reveal answer
intermediate
Can a method have both regular parameters and *args?

Yes. Regular parameters come first, then *args collects any remaining arguments.

Click to reveal answer
beginner
What happens if you call a method with *args but pass no extra arguments?

The args array will be empty, so the method still works without errors.

Click to reveal answer
What type of object is args inside a method defined with *args?
AHash
BString
CArray
DInteger
Which of these method definitions correctly uses *args?
Adef example(*args); end
Bdef example(args*); end
Cdef example(*args,); end
Ddef example(args); end
If a method is defined as def sum(*numbers), how do you call it with three numbers?
Asum([1, 2, 3])
Bsum(1, 2, 3)
Csum(1; 2; 3)
Dsum(1 2 3)
What will args.length return inside a method defined with *args if called with no arguments?
AError
Bnil
C1
D0
Can *args be used to accept keyword arguments?
ANo, <code>*args</code> only collects positional arguments
BYes, it collects keyword arguments
COnly if combined with <code>**kwargs</code>
DOnly if no positional arguments are passed
Explain how *args works in Ruby methods and give a simple example.
Think about how to accept many inputs without naming each one.
You got /3 concepts.
    Describe how you can combine regular parameters and *args in a method definition.
    Order matters in method parameters.
    You got /3 concepts.