简体   繁体   中英

Rewrite simple ruby function to use a block

I do not know the correct terminology. I tried to google it and could not find anything for that reason.

I am writing a Ruby library, and I want to rewrite the functions so they work as below as I prefer it for readability (inside a block?)

I have a function that does this

@dwg = Dwg.new("test.dwg")
@dwg.line([0,0,0],[1,1,0])
@dwg.save

I want to rewrite it so it works like this

Dwg.new("test.dwg") do

   line([0,0,0],[1,1,0])
   save

end

Can you outline the way I go about this?

You can define Dwg 's initializer to take a block, and then yield to that block with instance_eval , like so:

class MyClass
  def initialize(name, &block)
    @name = name
    instance_eval &block
  end

  def show_name
    puts 'My name is ' + @name
  end
end

MyClass.new('mud') do
  show_name
end

# >> My name is mud

For more information, see the "Blocks for Interface Simplification" section in the recently Creative-Commons-licensed Chapter 2 of Gregory Brown's excellent Ruby Best Practices book. (Its author and publisher are gradually CCing the entire thing, but you can of course still buy a copy to support the work. The iPhone edition is particularly affordable.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM