Tuesday, 7 August 2012

Difference between collect and collect!




Collect and collect!

here is an exapmle:


1.9.3p194 :001 > a=[1,2,3]

1.9.3p194 :003 > puts a.collect{|x| x * 3 }
3
6
9
 => nil
1.9.3p194 :004 > puts a
1
2
3
 => nil
1.9.3p194 :005 > puts a.collect!{|x| x * 3 }
3
6
9
 => nil
1.9.3p194 :006 > puts a
3
6
9
 => nil

So, when we use "collect" a dummy array is created and that will be changed.. but not the original array 'a' . Where as in collect!.... original array itself get changed.


No comments:

Post a Comment