lec21 - # duck typing # # (first, see lec20.rb for how...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#### duck typing #### # # (first, see lec20.rb for how double1 and double2 make different # assumptions about their arguments) # # silly example def foo(x,y) x.m(y) + y.n(3,"x") end # good that callee does not require particular classes -- more reuse # but makes it much harder to find equivalent bodies # #### block, iterators, Procs #### # def play # many library methods "take a block", which is essentially a closure # avoids many uses of explicit loops # (more concise, separates traversal from processing) 3.times { puts "hi" } [4,6,8].each { puts "hi" } # can "ignore" argument y = 7 [4,6,8].each { |x| y = y + x puts y } arr = [4,6,8,10] arr2 = arr.map { |x| x + 1 } puts "map result " puts arr2 sum = arr.inject { |acc,elt| acc + elt } puts "inject result " puts sum puts (arr.any? { |elt| elt < 0 }) # if only the immediate callee needs the block, # convenient to use the "yield" language feature (how the methods # above are implemented) puts (foo { |x| x + x }) # lambda is a built-in method that returns a Proc that is
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

lec21 - # duck typing # # (first, see lec20.rb for how...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online