Sunday 15 February 2015

Procs From "Understanding Ruby Blocks, Procs, and Lambdas" Article -



Procs From "Understanding Ruby Blocks, Procs, and Lambdas" Article -

ok, reviewing procs, lambdas, , blocks via link.

question on code:

class array def iterate! self.each_with_index |n, i| self[i] = yield(n) end end end array = [1, 2, 3, 4] array.iterate! |n| n ** 2 end puts array.inspect

conceptually, understand everything, except 1 line this:

self[i] = yield(n)

i self in line self.each_with_index |n, i| means it's class method, right?

but why need assign parameters in yield(n) self[i]?

please explain in super basic way if can.

(in other words, please nice - people part here - little nervous i'm not getting making me sense stupid)

the method iterate!, instance method. self in self.each_with_index receiver of method enumerable#each_with_instance. since self current instance of array ([1,2,3,4] in example), self. not needed; i.e., (and imo, should) write each_with_index |n, i|.... in other words, self implied receiver when no explicit receiver specified.

regarding line:

self[i] = yield(n)

for illustration array = [1,2,3,4] enumerator is:

enum = [1,2,3,4].each_with_index #=> #<enumerator: [1, 2, 3, 4]:each_with_index>

with elements

enum.to_a #=> [[1, 0], [2, 1], [3, 2], [4, 3]]

the first element passed block array#each hence [1,0], assigned block variables:

n = 1 = 0

resulting in

self[0] = yield(1) => 1**2 => 1

and on.

ruby lambda proc

No comments:

Post a Comment