基本语法,请参考相关书籍,这里只是对ruby进行一个概括的解读
包含其它的文件
这里讲的功能就好比java中的import功能,在ruby中使用如下的语法:
load "filename.rb" require "filename" |
require 是一个“executable statement”,所以它就好像一个函数一样,可以被放到if语句中,
参数也可以是按某种条件临时生成的文件名。
如下是一段英文解释:
The load method includes the named Ruby source file every time the method is executed,
whereas require loads any given file only once. require has additional functionality: it can
load shared binary libraries.
Modules概念
Modeles其实就是一个命名空间,其中可以包含方法、类、常量等。下面是Modules的英文概念:
Modules are a way of grouping together methods, classes, and constants. Modules give you two
major benefits:
1 Modules provide a namespace and prevent name clashes.
2 Modules implement the mixin facility.
下面是一个例子:
Module Notes |
异常的概念
异常在所有的语言中都是比较重要的一个内容。
先看一段异常处理的简单代码:
f = File.open("testfile") begin # .. process rescue # .. handle error else puts "Congratulations-- no errors!" ensure f.close unless f.nil? end |
现在以Java的类比来解释Ruby的异常:
Ruby |
| Java |
begin | --》 | try |
rescue | --》 | catch |
ensure | --》 | Finally |
else |
| Java中没有 |
接住具体异常的代码如下:
begin eval string rescue SyntaxError, NameError => boom print "String doesn't compile: " + boom rescue StandardError => bang print "Error running script: " + bang end |
抛出异常:
raise raise "bad mp3 encoding" raise InterfaceException, "Keyboard failure", caller |
线程的概念
线程的简单的例子
代码如下:
param = "hello, world" Thread.new(param){ puts "I'm running thread, and the params is : " + param } |
说明:Ruby中的线程创建就立即运行,没有像java那样只有调用了start方法才开始启动。
但是如下的代码起到了java中的效果:
param = "hello, world" t = Thread.new(param){ Thread.stop puts "I'm running thread, and the params is : " + param } ... t.run |
多线程和线程变量的例子:
count = 0 arr = [] 10.times do |i| arr[i] = Thread.new { sleep(rand(0)/10.0) Thread.current["mycount"] = count count += 1 } end arr.each {|t| t.join; print t["mycount"], ", " } puts "count = #{count}" |
说明:
1. 线程中可以使用线程的变量,Thread.current,它是一个hash
2. t.join方法 能够确保在在主程序退出前运行完所有的执行了join的线程,相关英文解释如下:
When a Ruby program terminates, all running threads are killed, regardless of their states.
However, you can wait for a particular thread to finish by calling that thread's Thread#joinmethod.
The calling thread will block until the given thread is finished. By calling join on each of the
requestor threads, you can make sure that all three requests have completed before you terminate
the main program.