ruby很多文法和特別這個動態特性都讓我想起oracle
ruby可以通過eval(“2+2”)==》4,執行動態代碼
eval的兄弟banding:
def eval_first puts eval("2+2") end def binding_elsewhere x=20 return binding end def eval_binding remote_binding = binding_elsewhere eval("puts x",remote_binding) eval("x=10") eval("x=50",remote_binding) eval("puts x") eval("puts x",remote_binding) end
輸出:20 10 50
其中eval有其他擴充形式:
class_eval:在類環境中執行代碼
class Person def add_accessor(accessor_name) self.class_eval %Q{ attr_accessor :#{accessor_name} } end endp = Person.newp.add_accessor :namep.name = "huang"puts p.name
還有module_eval和instance_eval
在ruby中可以運行其他程式
三種方法:system,%x{},反引號``
試下在irb中輸入:x=system("date")
移交執行權,用exec "ruby XXX.rb",終止當前程式運行,跳轉到其他程式。
exec “ruby another_rb.rb”puts "this will never be displayed"
同時運行兩個程式(難道傳說中的多線程)
利用kernel模組的方法fork,在父進程中返回子進程ID(注意fork對windows平台不可用)
child = fork do sleep 3 puts "child say XXXX"endputs "waiting for the child process"Process.wait childputs "all done!!"
兩程式互動:
ruby的IO模組提供一個popen方法
dir = IO.popen("dir","r")while line = dir.gets puts lineenddir.close
handle = IO.popen("other_program","r+")handle.puts "send input to other program"handle.close_writewhile line = handle.gets puts lineend
防止你利用動態代碼幹壞事,ruby採取了一些安全措施
tainted?判斷是否被感染的代碼
$SAFE設定安全層級