From: Wilson Bilkovich Date: 2006-03-08T11:01:29+09:00 Subject: Re: Passing the same argument(s) to several methods at once On 3/7/06, Iv�n Vega Rivera wrote: > Thanks but could you explain me a little bit more how that works? Ruby > says 'block' is undefined. So I'm missing something. > > The problem is I don't quite understand how that code works :-) > > Ivan V. > > On 3/7/06, ara.t.howard@noaa.gov wrote: > > > > the general case is: > > > > %w( function_a function_b ).each{|m| receiver.send(m, *args, &block)} > > > > works for any number of args, any receiver, and any block or lack of. > > %w(function_a function_b) creates an Array that looks like this: ['function_a', 'function_b'] 'each' is an instance method of Array (via the Enumerable module) that, when given a block, 'passes' each entry of the array to the block one by one. In this case, the block variable is 'm', and so 'm' will be the string 'function_a', and then the string 'function_b'. Let's modify your original example a little to show what object 'function_a' and 'function_b' are methods on. someobject.function_a('something') someobject.function_b('something') ..and let's rename that block variable to make what is going on a little clearer: %w(function_a function_b).each {|message| someobject.send(message, 'something')} By 'general case', Ara means that someobject.send(m, *args, &block) will handy any kind of method signature that 'm' might happen to have, no matter how many parameters it expects. Methods can choose to explicitly accepts blocks as parameters in Ruby, though it's a little uncommon in typical code. 'send' invokes a method by name, which is handy for this kind of thing.