作用域:指的是类,模块,方法
常量:无需指定类型,全大写
FANS = 100
puts "We have" + FANS.to_s + "fans"
变量
局部变量: 必须以小写字母开关或者下划线开头,离开作用域则失效, 如:
info = "这里局部变量"
_info = "这也是局部变量"
Class Test
_info = "我是在类中被定义成局部变量,作用域在类中"
puts _info
end module ModuleInfo
_info = "我是在模块中被定义成局部变量,作用域在模块中"
puts _info
end def
_info = "我是在方法中被定义成局部变量,作用域在方法中"
puts _info
end
全局变量: 作用于全局,任何地方都可以定义全局变量,可以在类,方法,模块中访问,以$开头
$info = "我是全局变量" def info
puts $info
end module ModuleInfo
puts $info
end class Test
puts $info
end
循环语句
While循环
row = 1
while(row <=9) do
row = row + 1
puts "this is" + (row-1).to_s + "print value is:" + row.to_s
end
until只有条件为fales时才会执行里面内容
row = 0
flh=["red", "orange", "yellow", "green"]
until(row >=7) do #when false enter until selection
flh.each do |h|
row = row + 1
puts h.to_s
end
end
for 循环
for...in 作用于数组和Hash
打印数组
shiren=["hello","world"]
for shijun in shiren do
puts shijun
end
打印hash
angle={"name" => "rocky", "address"=> "suzhou"}
for key, val in angle do
puts key + "is:" + key + "value is:" + val
end
迭代器语法:
Array.each do |定义的变量名|
代码块
end
例子:
names=["Eric", "Rocky", "James"]
names.each do |name|
puts name
end