Is it possible to alter the code inside a proc?

时间:2015-07-29 00:32:48

标签: ruby proc

to_source provided by the sourcify gem.

I wonder how would one would create these methods?

display: none;

I'd be interested in the hello = Proc.new{ 2.times{ puts 'hi' } } hello.to_source #=> 2.times{ puts 'hi' } hello.call #=> 'hi' 'hi' hello.change_hi_to_bye! hello.to_source #=> 2.times{ puts 'bye' } hello.call #=> 'bye' 'bye' hello.get_rid_of_block! hello.to_source #=> 2.times hello.call #=> method. Something generic that could strip all the blocks out of all the methods in a proc.

I've had a breif look into get_rid_of_block! with a view to altering the build sequence (thought there'd be a nice little RubyVM::InstructionSequence.of(my_proc).to_a field I could delete, but unfortunately not that I could see.

1 个答案:

答案 0 :(得分:0)

您可以使用method_missing(http://ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing)提供这些或类似的方法。只需将方法名称视为字符串,将其拆分为' _'并做一些你需要的东西。它是某种建筑商'模式实施。