Ruby有File类,可以使用普通的new()方法初始化,或者使用open()并传递一个块.我怎么写一个表现得像这样的课? File.open("myfile.txt","r") do |f|...end 这是将块传递给new / open方法的简单示例 class
File.open("myfile.txt","r") do |f| ... end这是将块传递给new / open方法的简单示例
class Foo def initialize(args, &block) if block_given? p block.call(args) # or do_something else #do_something else end end def self.open(args, &block) if block_given? a = new(args, &block) # or do_something else #do_something else end ensure a.close end def close puts "closing" end end Foo.new("foo") { |x| "This is #{x} in new" } # >> "This is foo in new" Foo.open("foo") { |x| "This is #{x} in open" } # >> "This is foo in open" # >> closing