ruby學習之動態代碼

來源:互聯網
上載者:User

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設定安全層級

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.