开发者

Rewrite simple ruby function to use a block

I do not know the corre开发者_运维知识库ct 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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜