On Wed, Nov 30, 2011 at 2:00 PM, Gaurav C. <chande.gaurav / gmail.com> 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)