Dynamic code for Ruby Learning

Source: Internet
Author: User

Many Ruby syntaxes and special dynamic features remind me of oracle.

Ruby can execute dynamic code through eval ("2 + 2") = 4

Eval brother 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

Output: 20 10 50

 

Among them, Eval has other extensions:

Class_eval: execute code in the class environment

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

There are also module_eval and instance_eval

 

Other programs can be run in ruby.

Three methods: system, % x {}, backticks''

Enter x = system ("date") in IRB ")

 

Hand over the execution right and use EXEC "Ruby XXX. RB" to terminate the current program and jump to another program.

exec “ruby another_rb.rb”puts "this will never be displayed"

 

Run two programs at the same time (is it the legend of multithreading)

Use the method fork of the kernel module to return the child process ID in the parent process (note that fork is unavailable to Windows)

child =  fork do    sleep 3    puts "child say XXXX"endputs "waiting for the child process"Process.wait childputs "all done!!"

Interaction between two programs:

The ruby Io module provides a popen method.

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 takes some security measures to prevent you from using dynamic code to do bad things.

Tainted? Code used to determine whether the website is infected

$ Safe: Set the security level

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.