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