ruby学习之动态代码

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设置安全级别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值