defcall_block(&block) #'&'表示把代码块作为闭包传递给函数 block.call end defpass_block(&block) call_block(&block) end pass_block{puts '...'}
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classTree attr_accessor:children,:node_name definitialize(name,children=[]) #初始化新对象时调用 @children=children @node_name=name end defvisit_all(&block) visit &block children.each(|c| c.visit_all &block) end defvisit(&block) block.call self end end
moduleToFile deffilename "object_#{self.object_id}.txt" end defto_f File.open(filename,'w'){|f|f.write(to_s)} end end classPerson includeToFile attr_accessor:name definitialize(name) @name=name end defto_s name end end Person.new('matz').to_f
classActsAsCsv defread file=File.new(self.class.to_s.downcase+'.txt') @headers=file.get.chomp.split(', ') file.each do |row| @result<<row.chomp.split(', ') end end defheaders @headers end defcsv_contents @result end definitialize @result=[] read end end classRubyCsv<ActsAsCsv end m=RubyCsv.new puts m.headers.inspect puts m.csv_contents.inspect
classActsAsCsv defself.acts_as_csv define_method"read"do file=File.new(self.class.to_s.downcase+'.txt') @headers=file.gets.chomp.split(', ') file.each do |row| @result<<row.chomp.split(', ') end end define_method"headers"do @headers end define_method"csv_contents"do @result end define_method"initialize"do @result=[] read end end end classRubyCsv<ActsAsCsv acts_as_csv end m=RubyCsv.new puts m.headers.inspect puts m.csv_contents.inspect
moduleActsAsCsv defself.included(base) base.extendClassMethods end moduleClassMethods defacts_as_csv includeInstanceMethods end end moduleInstanceMethods defread @csv_contents=[] filename=self.class.to_s.downclass+'.txt' file=File.new(filename) @headers=file.gets.chomp.split(', ') file.each do |row| @csv_contents<<row.chomp.split(', ') end end attr_accessor:headers, :csv_contents definitialize read end end end classRubyCsv includeActsAsCsv acts_as_csv end m=RubyCsv.new puts m.headers.inspect puts m.csv_contents.inspect