From: Josh Cheek Date: 2011-12-01T09:57:49+09:00 Subject: Re: Is high-speed sorting impossible with Ruby? --0016e6d99bd00c3b4c04b2fd3df1 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Nov 30, 2011 at 2:00 PM, Gaurav C. wrote: > > What's the difference between Array.new(1e6+1) {|n| ""} and > > Array.new(1e6+1, "")? > > Okay. Thanks all who explained this. > But, again, why is it better to use the former in this case? > > -- > Posted via http://www.ruby-forum.com/. > > As an analogy: If Jerry, Bob, and sally live in different houses, and you blow Jerry's house up, then only Jerry is homeless. If Jerry, Bob, and Sally live in the same house, and you blow Jerry's house up, then Jerry, Bob, and Sally are all homeless. As code: # each get's their own house houses = Array.new(3) { '' } houses.first << 'kaboom' houses # => ["kaboom", "", ""] # each lives in the same house houses = Array.new 3, '' houses.first << 'kaboom' houses # => ["kaboom", "kaboom", "kaboom"] Something you should try yourself: Try initializing each index to a random value between 1 and 10 (you can get this number with `rand(10)`). What behaviour explains the results you see? Can you write your own method that behaves the same way? (If you don't know how to deal with the blocks, try watching Ruby Kickstart session 3 http://ruby-kickstart.com/#session3) --0016e6d99bd00c3b4c04b2fd3df1--