執(zhí)行 ruby
- ruby 文件
# hello.rb
print("hello, Ruby .\n")
- 控制臺用 ruby 執(zhí)行文件($代表控制臺執(zhí)行,不是命令)
$ ruby hello.rb
- 直接在控制臺打開 ruby 環(huán)境
$ irb
字符串
print ("hello \n world")
print ('hello \n world')
在雙引號里 \是轉(zhuǎn)義字符,\n會換行,在單引號里\會當(dāng)成字符串輸出
方法調(diào)用
print ("hello world")
print "hello world"
print "hello", "world"
方法調(diào)用參數(shù)可以省略括號
輸出
print "hello world"
puts "hello world"
p "100"
p 100
print 不會換行,puts輸出后換行,p 能看到原始的數(shù)據(jù)格式
編碼
# encoding: GBK
print "饑人谷"
對于中文,如果文件保存的是 GBK,則需要指明編碼方式為 GBK
$ ruby -E UTF-8 hello.rb
$ irb -E UTF-8
變量
a = 1.5
name = "饑人谷"
age = 3
isOk = true
obj = {"name"=>"饑人谷", "age"=>3}
p obj["name"]
變量無需聲明類型
變量與雙引號
width = 100
height = 200
puts "寬度: #{width}, 高度:#{height}, 面積: #{width*height}"
注釋
# 這是單行注釋
=begin
這是大段
注釋
=end
條件判斷
score = 80
if score >= 90 then
puts "優(yōu)秀"
elsif score >=80 then
puts "良"
elsif score >=60 then
puts "及格"
else
puts "不及格"
end
while
i = 1
while i<10
puts i
# i++ 錯誤
# i += 1 正確
i = i + 1 #正確
end
times
i = 1
100.times do
puts i
i += 1
end