Ruby: does the class accept a block?

I noticed that the CSV class in Ruby has some quick access interfaces (see http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html ):

CSV             { |csv_out| csv_out << %w{my data here} }  # to $stdout
CSV(csv = "")   { |csv_str| csv_str << %w{my data here} }  # to a String
CSV($stderr)    { |csv_err| csv_err << %w{my data here} }  # to $stderr
CSV($stdin)     { |csv_in|  csv_in.each { |row| p row } }  # from $stdin

Is there a way to do this for my own classes? I am implementing DSL and this will make the code much cleaner.

+5
source share
2 answers

This is not a class. This is a method defined on Object(although there is a class called with the same name CSV). The document you linked is misleading. This explains it better.

You cannot do this with a module, but you can define a method that takes a block.

+6
source

. , , . sawa , .

Ruby 2.0 .

Object, .

Ruby 1.9, , .

, , -.

+1

All Articles