How do you stringize/serialize Ruby code?

前端 未结 4 494
后悔当初
后悔当初 2020-12-16 13:32

I want to be able to write a lambda/Proc in my Ruby code, serialize it so that I can write it to disk, and then execute the lambda later. Sort of like...

x          


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 14:14

    Use sourcify

    This will work on Ruby 1.8 or 1.9.

    def save_for_later(&block)
      block.to_source
    end
    
    x = 40
    s = save_for_later {|y| x + y }
    # => "proc { |y| (x + y) }"
    g = eval(s)
    # => #
    g.call(2) 
    # => 42
    

    See my other answer for capturing free variables.

    Update: Now you can also use the serializable_proc gem, which uses sourcify, and captures local, instance, class, and global variables.

提交回复
热议问题