Friday, May 23, 2008

closure tip

closure is so fun.
well design for meta programming.

note 1:

01 #!/usr/bin/env ruby
02
03 class Hash
04 def find_all
05 temp_hash = {}
06 each {|key,value| temp_hash[key] = value if yield(key,value) }
07 temp_hash
08 end
09 end
10
11 square = { 0 => 0, 1 => 1, 2 => 4, 3 => 9 }
12
13 new = square.find_all { |key,value| key > 1 }
14 puts new.inspect

pass yield values.

note 2:

01 #!/usr/bin/env ruby
02
03 class Person
04 attr_accessor :name
05 def initialize(name)
06 @name = name
07 end
08 end
09
10 def command(obj,method)
11 obj.each {|x| yield x.send(method)}
12 end
13
14 family = []
15
16 %w(shelling sherry appollo).each do |name|
17 family.push Person.new(name)
18 end
19
20 command family, :name do |x|
21 puts "hello, I am #{x}."
22 end

Every object in array call the same function.

 
 

No comments: