下载 Ruby:http://rubyforge.org/frs/?group_id=167
安装 Rails:gem install rails --remote
安装 Mysql 驱动:gem install mysql
第一部分 Ruby/Rails 全景
第一章 Ruby 工作原理
一、编写第一个程序文件:
1. 摄氏—华氏温度转换程序(F:\ruby_project\c2f.rb)
c = 100
f = (c * 9 / 5) + 32
puts "The result is: "
puts f
puts "."
2. 语法错误检查
F:\ruby_project>ruby -cw c2f.rb
Syntax OK
3. 运行程序
F:\ruby_project>ruby c2f.rb
The result is:
212
.
二、交互式温度转换程序(F:\ruby_project\c2fi.rb)
print "Hello. Please enter a Celsius value: "
c = gets
f = (c.to_i * 9 / 5) + 32
puts "The Fahrenheit equivalent is "
puts f
puts "."
===================================================
缩减代码:
print "Hello. Please enter a Celsius value: "
print "The Fahrenheit equivalent is ", gets.to_i * 9 / 5 + 32, ".\n"
===================================================
F:\ruby_project>ruby c2fi.rb
Hello. Please enter a Celsius value: 100
The Fahrenheit equivalent is 212.
F:\ruby_project>ruby c2fi.rb
Hello. Please enter a Celsius value: 23
The Fahrenheit equivalent is 73.
三、文件输入式温度转换程序(F:\ruby_project\c2fin.rb)
print "Reading Celsius temperature value from data file..."
num = File.read("temp.dat")
c = num.to_i
f = (c * 9 / 5) + 32
puts "The number is " + num
print "Result: "
puts f
四、使用文件输出的温度转换程序(F:\ruby_project\c2fout.rb)
print "Hello. Please enter a Celsius vallue: "
c = gets.to_i
f = (c * 9 / 5) + 32
puts "Saving result to output file 'temp.out'"
fh = File.new("temp.out", "w")
fh.puts f
fh.close
五、一个程序,多个文件
1. 请求加载文件 require:
puts "This is the first (master) program file."
require 'requiree.rb'
puts "And back again to the first file."
2. 加载文件 load:
load 是 require 的近亲。它们的主要区别在于,如果执行下面代码:
require 'requiree.rb'
require 'requiree.rb'
第二次执行 require 什么都不会发生,而如果执行下面代码:
load 'requiree.rb'
load 'requiree.rb'
Ruby 会两次读入该文件
六、ruby 解释起的命令行开关
命令行开关 | 描述 | 例子 |
-c | 不执行程序,只检查程序语法 | ruby -c c2f.rb |
-w | 在程序执行过程中给出警告信息 | ruby -w c2f.rb |
-e | 执行在命令行中引号内的代码 | ruby -e 'puts "code demo!"' |
-v | 显示Ruby版本信息,在详细模式下执行程序 | ruby -v |
-l | 行模式:如果没有换行则在每一行后输出换行 | ruby -l -e 'print "Will jump!"' |
-rname | 加载指定的扩展 | ruby -r profile |
--version | 显示Ruby版本信息 | ruby --version |
七、重要的标准 Ruby 工具和应用程序
1. 调试器,Ruby 运行这个例子时加载了 debug 扩展
F:\ruby_project>ruby -r debug c2fi.rb
Debug.rb
Emacs support available.
2. 性能分析
F:\ruby_project>ruby -r profile c2fi.rb
3. ri和RDoc
(1)ri(Ruby 索引):命令行工具,获取关于Ruby的详细信息,如:
(2)RDoc(Ruby 文档):根据注释内容建立索引
4. ERb (Embedded Ruby):允许将 Ruby 代码嵌入 HTML 文件
(1)ERb 实例(erbdemo.rb)
<% page_title = "Demonstration of ERb" %>
<% salutation = "Dear programmer," %>
<html>
</html>
(2)F:\ruby_project>erb erbdemo.rb
<html>
</html>