Y-combinator.
f = Y do |n, acc, &b| n < 2 ? acc : b.(n-1, n * acc) end f.call(5, 1) #=> 120
NOTE: This is not (presently) a common core extension and is not loaded automatically when using require 'facets'.
CREDIT: Michael Fellinger
# File lib/facets/core-uncommon/facets/kernel/y.rb, line 16 def Y(*args, &block) y = lambda{|*args| block.call(*args, &y) } end
For debugging and showing examples. Currently this takes an argument of a string in a block...
demo {%{ a = [1,2,3] }} demo {%{ a.slice(1,2) }} demo {%{ a.map { |x| x**3 } }}
produces ...
a = [1,2,3] #=> [1, 2, 3] a.slice(1,2) #=> [2, 3] a.map { |x| x**3 } #=> [1, 8, 27]
TODO: Is there a way to do this without the eval string in block? Preferably just a block and no string.
NOTE: This is not (presently) a common core extension and is not loaded automatically when using require 'facets'.
# File lib/facets/core-uncommon/facets/kernel/demo.rb, line 22 def demo(out=$stdout,&block) out << sprintf("%-25s#=> %s\n", expr = block.call, eval(expr, block.binding).inspect) end
Memoize a method.
class MemoExample attr_accessor :a def m memo{ @a } end end ex = MemoExample.new ex.a = 10 ex.m #=> 10 ex.a = 20 ex.m #=> 10
NOTE: This is not (presently) a common core extension and is not loaded automatically when using require 'facets'.
# File lib/facets/core-uncommon/facets/kernel/memo.rb, line 29 def memo(*args, &block) if args.empty? args = block.binding.eval('[self, __method__]') end if $MEMO.key?(args) $MEMO[args] else $MEMO[args] = block.call end end
Calling Kernel#trap() by itself will replace any previously registered handler code. Kernel#trap_chain(), on the other hand, will add the block you supply to the existing "list" of registered handler blocks. Similar to the way Kernel#at_exit() works, Kernel#trap_chain() will prepend the given block to the call chain for the given signal_name. When the signal occurs, your block will be executed first and then the previously registered handler will be invoked. This can be called repeatedly to create a "chain" of handlers.
NOTE: This is not (presently) a common core extension and is not loaded automatically when using require 'facets'.
CREDIT: Tyler Rick
# File lib/facets/core-uncommon/facets/kernel/trap_chain.rb, line 15 def trap_chain(signal_name, *args, &block) previous_interrupt_handler = trap(signal_name, *args) {} trap(signal_name, *args) do block.call previous_interrupt_handler.call unless previous_interrupt_handler == "DEFAULT" end end
Generated with the Darkfish Rdoc Generator 2.