特性:
一种真正的面向对象脚本编程语言。
支持许多 GUI 工具,比如 Tcl/Tk、GTK 和 OpenGL。
很容易地连接到 DB2、MySQL、Oracle 和 Sybase。
有丰富的内置函数。
可以用来编写通用网关接口(CGI)脚本。
可用于开发的 Internet 和 Intranet 应用程序。
可以被嵌入到超文本标记语言(HTML)。
交互式命令行的模式: irb
命令行选项:
-c 只检查语法,不执行程序。
-C dir 在执行前改变目录。
-d 启用调试模式(等价于 -debug)。
注释: 单行 # 多行 =begin……=end
#!/usr/bin/ruby
# encoding:utf-8
# 输出
print("hello,ruby\n")
puts "hello","ruby"
puts "100"
p "100"
# 控制
a=20
if a>=10 then
puts "bigger"
end
if a<10 then
puts "smaller"
end
#
a=5
if a>=10 then
puts "bigger"
else
puts "smaller"
end
#
i=1
while i<=10
print i,","
i=i+1
end
#
3.times do |i|
print "rudy #{i}\n"
end
#
names=["梁","梁志","远"]
puts names.size
names.each do |n|
puts n
end
#
address={name:"梁志远",tel:"152"}
puts address[:name]
puts address[:tel]
address.each do |key,value|
puts "#{key}:#{value}"
end
#
names=["梁","梁志","远"]
names.each do |n|
if /梁/=~n
puts n
end
end
# ruby hello.rb hello world
puts "参数1:#{ARGV[0]}"
puts "参数2:#{ARGV[1]}"
# ruby hello.rb test.txt
filename =ARGV[0]
file = File.open(filename)
text = file.read
puts text
file.close
# ruby hello.rb test.txt
filename =ARGV[0]
text = File.read(filename)
puts text
# ruby hello.rb test.txt
puts File.read(ARGV[0])
# ruby hello.rb test.txt
filename =ARGV[0]
file = File.open(filename)
file.each_line do |line|
puts line
end
file.close
# ruby hello.rb 语言 test.txt
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
file = File.open(filename)
file.each_line do |line|
if pattern =~ line
puts line
end
end
file.close
# 方法定义
def hello
puts "hello ruby"
end
hello()
#
require "date"
days=Date.today-Date.new(2015,7,20)
puts days.to_i
#
require "grep"
grep_demo(Regexp.new("Ruby"),"test.txt")
#
arr=["a",1,nil]
arr.each do |item|
case item
when String
puts "is String"
when Numeric
puts "is Numeric"
else
puts "nil"
end
end
#
from =1
to=10
sum=0
for i in from..to
sum+=i
end
puts sum
#
def myloop
while true
yield
end
end
num=1
myloop do
if num >100 then
break
end
puts "num is #{num}"
num *=2
end
#
def meth(arg,*args,c)
[arg,args,c]
end
p meth(1,2,3,4)
#面向对象
require "net/http"
require "uri"
#url = URI.parse("http://www.ruby-lang.org/ja/")
url = URI.parse("http://www.sina.com.cn/")
http = Net::HTTP.start(url.host,url.port)
doc = http.get(url.path)
puts doc
#类和实例
arr = Array.new
arr2 = []
str=""
p arr
p arr.class
p str.class
p arr.instance_of?(Array)
p str.instance_of?(String)
#类
class Hello
def initialize(myname="ruby")
@name=myname
end
def hello
"hello,world.i am #{@name}"
end
end
bob = Hello.new("bob")
p bob.hello
p Hello.new.hello
#继承
str=""
p str.is_a?(String)
p str.is_a?(Object)
class RingArray < Array
def [] (i)
idx = i% size
super(idx)
end
end
wday=RingArray["周一","周二","周三","周四","周五"]
p wday[3]
p wday[7]
#封装
t=Time.new
p t.year
#多态
obj=Object.new
srt="hello"
num=Math::PI
p obj.to_s
p srt.to_s
p num.to_s
#扩展类
class String
def count_word
arr=self.split(/\s+/)
return arr.size
end
end
p "h e l l o".count_word
#单例类
str="ruby"
class <<str
def hello
"hello,#{self}"
end
end
p str.hello
#include
module M
def meth
"meth"
end
end
class C
include M
end
p C.new.meth
p C.include?(M)
p C.ancestors
p C.superclass
#extend
module Edition
def edition(n)
"#{self} 第#{n}版"
end
end
str = "Ruby"
str.extend(Edition)
p str.edition(4)
#extend/include
module ClassMethods
def cmethod
"class method"
end
end
module InstanceMethods
def imethod
"instance method"
end
end
class MyClass
extend ClassMethods
include InstanceMethods
end
p MyClass.cmethod
p MyClass.new.imethod
# 异常
def copy(from,to)
num=1
begin
src = File.open(from)
#raise "打开文件失败"
dst = File.open(to,"w")
data = src.read
dst.write(data)
dst.close
rescue => ex
p ex.message
while num < 5 do
sleep 1
num += 1
retry
end
ensure
p "尝试 #{num}次"
src.close
end
p "over"
end
copy("text.txt","text.txt")
#块
sum = 0
items =""
outcome = {"通讯费"=>58,"书费"=>300,"交通费"=>100}
outcome.each do |item , price|
items += item+"-"
sum += price
end
puts "#{items}:#{sum}"
# 将块封装为对象
hello = Proc.new do |name|
puts "Hello,#{name}"
end
hello.call("World")
#
def total(from,to)
result =0
from.upto(10) do |num|
if block_given?
result += yield(num)
else
result+=num
end
end
return result
end
p total(1,10)
p total(1,10){|num| num**2}
sum=0
n = total(1,10) do |num|
if num ==5
next 0
end
num
end
p n
#数值类
a=Rational(2,5)
b=Rational(1,3)
p a
p b
c=a+b
p c
p c.to_f
p Random.rand
p Random.rand(10)
# 数组类、字符串类、散列类
# 正则表达式类
str = "http://www.ruby-lang.org/ja/"
%r|http://([^/]*)/|=~str
puts "server address #{$1}"
str2 = "http://www.ruby-lang.org/ja/?name=bar#lzy"
%r|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?|=~str2
puts "#{$2},#{$4},#{$5},#{$7},#{$9}"
#IO类、File类、Dir类
$stdout.print "out1"
$stderr.print "out1"
File.rename("test.txt","test2.txt")
Dir.mkdir("temp")
p Dir.pwd
#Encoding类
#Time类、Date类
require "time"
require "date"
p Time.new
sleep 1
p Time.now
p Time.now.strftime("%Y-%m-%d %H:%M:%S")
p Time.parse("2013/03/23 08:35:15")
d=Date.today
puts d
d1=Date.new(2013,6,8)
p d.strftime("%a %b %d %Y/%m/%d %H:%M:%S")
#Proc类
hello = Proc.new do |name|
puts "Hello,#{name}"
end
hello.call("World")
Ruby 数据库访问:mysql
1、安装 Ruby MySQL 模块
2、数据库连接
require "dbi"
begin
# 连接到 MySQL 服务器
dbh = DBI.connect("DBI:Mysql:数据库实例名:localhost",
"root", "mysql")
# 获取服务器版本字符串,并显示
row = dbh.select_one("SELECT VERSION()")
puts "Server version: " + row[0]
rescue DBI::DatabaseError => e
puts "Error code: #{e.err}"
ensure
# 断开与服务器的连接
dbh.disconnect if dbh
end
3、CRUD
do 方法
dbh.do("INSERT INTO EMPLOYEE(*) VALUES ('Mac', 'Mohan')")
dbh.commit
prepare 和 execute 方法
sth = dbh.prepare("INSERT INTO EMPLOYEE(*) VALUES (?, ?)")
sth.execute('John', 'Poul')
sth.execute('Zara', 'Ali')
sth.finish
dbh.commit
Ruby CGI 编程
1、配置Web服务器支持CGI。
2、编写 CGI 脚本。/test.cgi?FirstName=Liang
require 'cgi'
cgi = CGI.new
FirstName=cgi['FirstName']
puts cgi.header
puts "<html><body>#{FirstName}</body></html>"
Ruby 发送邮件
require 'net/smtp'
message = <<MESSAGE_END
From: xxx
To: xxx
Subject: title
content
MESSAGE_END
Net::SMTP.start('localhost') do |smtp|
smtp.send_message message, 'from','to'
end
Ruby Socket 编程
简单的客户端
require 'socket' # Sockets 是标准库
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # 从 socket 中读取每行数据
puts line.chop # 打印到终端
end
s.close # 关闭 socket
简单的服务端
require 'socket' # 获取socket标准库
server = TCPServer.open(2000) # Socket 监听端口为 2000
loop { # 永久运行服务
client = server.accept # 等待客户端连接
client.puts(Time.now.ctime) # 发送时间到客户端
client.puts "Bye!"
client.close # 关闭客户端连接
}
Ruby XML, XSLT 和 XPath
Ruby Web Services
Ruby 多线程
Ruby JSON 编码和解码 JSON 对象
Ruby RubyGems 包管理器
Ruby on Rails 是一个可以使你开发,部署,维护 web 应用程序变得简单的框架。