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
end
p = Person.new
p.add_accessor :name
p.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"
end
puts "waiting for the child process"
Process.wait child
puts "all done!!"
两程序交互:
ruby的IO模块提供一个popen方法
dir = IO.popen("dir","r")
while line = dir.gets
puts line
end
dir.close
handle = IO.popen("other_program","r+")
handle.puts "send input to other program"
handle.close_write
while line = handle.gets
puts line
end
防止你利用动态代码干坏事,ruby采取了一些安全措施
tainted?判断是否被感染的代码
$SAFE设置安全级别