Sunday, August 5, 2012

More on Blocks, Procs, and Lambdas -- Finding the Square Root of Numbers in an Array


1.9.3p194 :091?>class Array
1.9.3p194 :092?>   def iterate!
1.9.3p194 :093?>     self.each_with_index do |n,i|
1.9.3p194 :094 >         self[i] = yield(n)
1.9.3p194 :095?>       end
1.9.3p194 :096?>     end
1.9.3p194 :097?>   end
 => nil

1.9.3p194 :128 > array = [1,4,9,16]
 => [1, 4, 9, 16]
1.9.3p194 :129 > array.iterate! do |n|
1.9.3p194 :130 >     Math.sqrt(n)
1.9.3p194 :131?>   end
 => [1.0, 2.0, 3.0, 4.0]

Yes, I opened the class and altered it.


No comments:

Post a Comment