From: Ryan Davis Date: 2011-11-29T08:02:03+09:00 Subject: Re: Is high-speed sorting impossible with Ruby? On Nov 28, 2011, at 06:34 , Sylvester Keil wrote: > > On Nov 28, 2011, at 3:17 PM, Gaurav C. wrote: > >> Douglas Seifert wrote in post #1034017: >>>> >>>>> a = Array.new(1e6+1) {|n| ""} >>>> >>> >>> The above creates an Array of 1,000,001 slots. The block syntax lets >>> you >>> provide a default object dynamically. The first time you reference a >>> particular index in the array, the block is called to allocate the >>> default >>> object at that position. >>> >> >> Hi Doug, >> >> Thanks for the explanation. >> Didn't understand the Array initialization part. >> What's the difference between Array.new(1e6+1) {|n| ""} and >> Array.new(1e6+1, "")? > > The former always returns a new string instance (this is what you want); the former creates one string and always returns a reference. I don't think this really explains it adequately. The former initializes the array by running the block on every index. The latter assigns the same object to every index. From ri: Array.new(size=0, obj=nil) Array.new(array) Array.new(size) {|index| block } ------------------------------------------------------------------------------ Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element's index to the given block and storing the return value.