天天看點

ruby小例子-動态執行,綁定,線程

#encoding:utf-8
# ---------動态執行
#執行2 + 2
puts eval "2 + 2"
#=》4
#執行15 * 2 (Q表示雙引号會進行運算,q表示單引号會原樣輸出)
number = 15
code = %Q{#{number} * 2}
puts code
puts eval(code)
#=》4
#=》#{number} * 2

# ---------綁定
def binding_test
  return binding
end
binding_function = binding_test
x = 9
eval("x = 10")
eval("x = 50", binding_function)
#處理目前環境的局部變量
eval("puts x")
#處理binding環境的局部變量
eval("puts x", binding_function)


#exec "data.rb"
#puts "end"
#ruby的線程不是由作業系統來提供,由ruby解釋器來執行
#優點:跨平台性能很好
#缺點:如果需要調用作業系統并等待回應,則整個ruby程式就會暫停

#新開線程
child = fork do
  sleep 1
  puts "child ok"
end
puts "waiting for child process"
Process.wait child
puts "end"

#線程
#建立10個線程随機睡眠,列印 
threads = []
10.times do
  thread = Thread.new do
    10.times {|i| 
      print i
      $stdout.flush
      #轉讓線程執行權
      Thread.pass
      sleep 1
      }
  end
  threads <<thread
end
puts Thread.list.inspect
#join讓主線程等待至線程執行完畢
threads.each() do |thread|
  thread.join(3)
end