如何输入一段ruby代码然后执行它?(how to input a string of ruby code and execute the code)

访问量: 1476

there's a case that I have to input a string of ruby from console(or from even the web page) then execute it. here is the example: (如题。)

class UrlGenerator
    attr_accessor :urls
    def generate
        @urls = yield
    end 
end

puts "== input a block"
# input:  base_url = "/base" ;  switches = [1,2];     results = [] ;  switches.each { |i|   results << "#{base_url}/#{i}"  };  results;
block_string = gets
puts "===== block_string: #{block_string}"
the_block = lambda{eval(block_string)}
puts "== the block: #{the_block}"
a = UrlGenerator.new
a.generate &the_block
puts "==== urls: #{a.urls.inspect}"

refer to: http://siwei.me/blog/posts/block-basic-in-ruby, http://siwei.me/blog/posts/the-return-in-ruby

订阅/RSS Feed

Subscribe

分类/category