如何构建一个在传递块时自动初始化和销毁的Ruby类?

2026-04-11 16:081阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计256个文字,预计阅读时间需要2分钟。

如何构建一个在传递块时自动初始化和销毁的Ruby类?

Ruby 中,可以使用 `File.open` 方法来打开文件,并通过 `do...end` 块来执行文件操作。以下是一个简单的示例,展示如何使用 `File.open` 并将块传递给 `new` 或 `open` 方法:

rubyclass MyClass def initialize(file_path, mode) @file=File.open(file_path, mode) end

def read_file @file.read ensure @file.close if @file endend

使用 MyClassmy_file=MyClass.new(myfile.txt, r)puts my_file.read_file

Ruby有File类,可以使用普通的new()方法初始化,或者使用open()并传递一个块.我怎么写一个表现得像这样的课?

如何构建一个在传递块时自动初始化和销毁的Ruby类?

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

本文共计256个文字,预计阅读时间需要2分钟。

如何构建一个在传递块时自动初始化和销毁的Ruby类?

Ruby 中,可以使用 `File.open` 方法来打开文件,并通过 `do...end` 块来执行文件操作。以下是一个简单的示例,展示如何使用 `File.open` 并将块传递给 `new` 或 `open` 方法:

rubyclass MyClass def initialize(file_path, mode) @file=File.open(file_path, mode) end

def read_file @file.read ensure @file.close if @file endend

使用 MyClassmy_file=MyClass.new(myfile.txt, r)puts my_file.read_file

Ruby有File类,可以使用普通的new()方法初始化,或者使用open()并传递一个块.我怎么写一个表现得像这样的课?

如何构建一个在传递块时自动初始化和销毁的Ruby类?

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