0
0
Rubyprogramming~10 mins

Variable-length arguments (*args) in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a method that accepts any number of arguments.

Ruby
def greet([1])
  puts "Hello, #{args.join(', ')}!"
end
Drag options to blanks, or click blank then click option'
A*args
B&args
Cargs
D**args
Attempts:
3 left
💡 Hint
Common Mistakes
Using &args instead of *args, which is for blocks.
Using **args which is for keyword arguments.
Not using any symbol, which only accepts one argument.
2fill in blank
medium

Complete the code to call the method with multiple arguments.

Ruby
greet([1])
Drag options to blanks, or click blank then click option'
A"Alice", "Bob", "Carol"
B"Alice"
C["Alice", "Bob"]
D:Alice, :Bob
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an array instead of separate arguments.
Passing symbols instead of strings.
Passing only one argument when multiple are needed.
3fill in blank
hard

Fix the error in the method definition to correctly accept variable arguments.

Ruby
def sum_numbers([1])
  sum = 0
  args.each { |num| sum += num }
  sum
end
Drag options to blanks, or click blank then click option'
A&args
Bargs
C*args
D**args
Attempts:
3 left
💡 Hint
Common Mistakes
Using args without * causes an error because it expects one argument.
Using &args is for blocks, not variable arguments.
Using **args is for keyword arguments.
4fill in blank
hard

Fill both blanks to create a method that sums only positive numbers from variable arguments.

Ruby
def sum_positive([1])
  args.select { |n| n [2] 0 }.sum
end
Drag options to blanks, or click blank then click option'
A*args
B>
C>=
Dargs
Attempts:
3 left
💡 Hint
Common Mistakes
Using args without * causes errors.
Using >= includes zero, which is not positive.
Using < or <= selects negative or zero numbers.
5fill in blank
hard

Fill all three blanks to define a method that prints each argument with its index.

Ruby
def print_args([1])
  args.each_with_index do |[2], [3]|
    puts "#{index}: #{arg}"
  end
end
Drag options to blanks, or click blank then click option'
A*args
Barg
Cindex
Dargs
Attempts:
3 left
💡 Hint
Common Mistakes
Using args without * causes errors.
Swapping the order of block variables.
Using wrong variable names in the block.