1.輸出
puts "hello world" #或者p "hello world"
---------------------
2.註釋
#單行註釋
#puts "hello world"
#多行註釋
=begin
....
=end
---------------------
3.變量(小寫或下劃線開頭)
name = "崇慕"
num = "1" #字符串
num = 1 #數值
puts name
---------------------
4.字符串(常用三種)
"......" #內有變量起作用
'......' #內直接被轉移
%{.....} #針對多行
---------------------
5.運算符
puts 1+1 #輸出2
puts 1+"1" #輸出錯誤
puts 1+name #加字符串錯誤
---------------------
6.判斷if..else..end
#模式一
if a>b
puts "a大於b"
elsif a<b
puts "a小於b"
else
puts "a等於b"
end
#模式二
puts "a>b" if a>b
#模式三
puts "a>b" unless a<=b
---------------------
7.分支switch語法
i= "2"
case i
when 1
puts "一"
when "2"
puts "這個字符串"
else
puts "其他"
end
---------------------
8.循環
#循環while (數組)
while i<5 do
puts i
i+=1 #相當於i++
end
#循環for in 相當於php的foreach (數組)
for value in array do
puts ""
end
#數組迭代(循環)同上
array.each do |value| end
#(哈希)hash 迭代(循環)
hash.each do |key,value| end
#循環100次 (數值)
100.times do |i| end
---------------------
9.函數
array.length #計算數組長度
"asdasdasdad"[3..5] #截取字符串 [-3..-1]
def hello(name="我",say="")
return name+say #我
end
p hello("我","哈哈")
---------------------
10.post和get,session,cookie
params[:name]
session[:name]
cookies[:name]
?a=3&b=5
params[:a]
params[:b]
---------------------
11.日期
Time.now #現在時間 類大寫首字母
---------------------
12.引用
---------------------
13.文件
File.open("c:/a.txt","r") do |file|
p file.read
end
File.open("c:/a.txt","w") do |file|
file.write "學學學習學習"
end
---------------------
14.異常處理Exception
begin
#運行代碼
rescue
#錯誤後操作代碼
end
---------------------
15.編碼
irb(main):037:0> $KCODE='utf8'
=> "utf8"
irb(main):038:0> "號"
=> "號"
irb(main):039:0> "好的"
=> "好的"