From: Jacob Fugal Date: 2006-11-25T06:03:38+09:00 Subject: Re: what is *self? On 11/24/06, josefK wrote: > I encountered this added method to Array (I don't recall > the author - sorry ,) > It converts an Array to a Hash by providing a block to compute the > values given the array elements as keys: > > class Array > def to_h(&block) > Hash[*self.collect{|v| [v,block.call(v)]}.flatten] > end > end Vidar explained the general concept of the splat fairly well, but the following clarification of order of operations should help understand this particular application: # assuming self = [ 1, 2, 3 ] and block = proc{ |x| x**2 } self. collect{|v| [v,block.call(v)]}. # => [[1, 1], [2, 4], [3, 9]] flatten # => [1, 1, 2, 4, 3, 9] Without the star, the full Method body would be (equivalently): Hash[[1, 1, 2, 4, 3, 9]] This complains about an odd number of elements because it's receiving only one element -- the array. Adding the "splat" in essence removes the innermost pair of square brackets: Hash[1, 1, 2, 4, 3, 9] Hash#[] can then use the list as key/value pairs. As I said, Vidar explained the operation of the splat well, I just wanted to point out *which* array the star was operating on -- the result of the expression "self.collect{ ... }.flatten", not to self itself (no pun intended). Jacob Fugal