Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically pass args to yield in Ruby?

Tags:

ruby

How can I pass a variable number of args to a yield. I don't want to pass an array (as the following code does), I'd actually like to pass them as a programmatic number of args to the block.

def each_with_attributes(attributes, &block)
  results[:matches].each_with_index do |match, index|
    yield self[index], attributes.collect { |attribute| (match[:attributes][attribute] || match[:attributes]["@#{attribute}"]) }
  end
end
like image 533
Ben Crouse Avatar asked Nov 28 '08 22:11

Ben Crouse


People also ask

What do you use the keyword yield for * in Ruby?

yield tells ruby to call the block passed to the method, giving it its argument. yield will produce an error if the method wasn't called with a block where as return statement don't produces error.

How does yield work in Ruby on Rails?

The yield keyword, when used inside the body of a method, will allow you to call that method with a block of code and pass the torch, or yield, to that block. Think of the yield keyword as saying: "Stop executing the code in this method, and instead execute the code in this block.


2 Answers

Use the splat-operator * to turn the array into arguments.

block.call(*array)

or

yield *array
like image 150
Andru Luvisi Avatar answered Sep 18 '22 14:09

Andru Luvisi


Use the asterisk to expand an array into its individual components in an argument list:

def print_num_args(*a)
  puts a.size
end

array = [1, 2, 3]
print_num_args(array);
print_num_args(*array);

Will print:

1
3

In the first case the array is passed, in the second case each element is passed separately. Note that the function being called needs to handle variable arguments such as the print_num_args does, if it expects a fixed size argument list and received more or less than expected you will get an exception.

like image 29
Robert Gamble Avatar answered Sep 18 '22 14:09

Robert Gamble