继续ruby的学习,这次主要把目光放到运算符,条件判断,循环,方法,以及其他ruby特有的基本概念上
foo = 42; $VAR = 1
# 1.判断变量是否已经初始化
puts defined? foo # local-variable
puts defined? $VAR # global-variable
puts defined? bar # 未定义
# 2.判断方法是否已经定义
puts defined? puts # method
x = 1
if x>2
puts 'x > 2'
elsif x<=2 and x!=0
puts 'x = 1'
else
puts 'unknow x'
end
if后的条件成立才执行前面一句(比较灵活的写法)
a = 1
print a if a # 变量a被定义过了,所以返回true
与if刚好相反
age = 5
case age
when 0..2
puts '婴儿'
when 3..6
puts '小孩'
when 7..12
puts '少年'
else
puts '其他'
end
i = 0; num = 5
while i<num
puts i; i += 1
end
i = 0; num = 5
begin
puts i; i += 1
end while i<num
until与while完全相反
for i in 0..5
if i == 2
next # 相当于continue
elsif i == 4
break # 跳出循环
end
puts i
end
def test(a=1, b) # 可以使用默认参数
return a+b, a-b
end
sum, sub = test 2, 3
puts sum, sub
def sample (*test) # *号允许可变数量的参数
test.each do
|item|
puts item
end
end
sample 'a', 'b'
sample 1, 2, 3
class Accounts
def reading_charge
# dosomething
end
def Accounts.return_date
# 类方法
end
end
Accounts.return_date # 类方法调用
alias 方法名 方法名
alias 全局变量 全局变量
undef 方法名
块在ruby中用{}包裹,也可以用do end形式
# 定义函数
def myloop
while true
yield
end
end
num = 1
# 执行myloop函数时,会把块中内容挂载到yield处
myloop do
puts "num is #{num}"
break if num > 100
num *= 2
end
# 运行结果
num is 1
num is 2
num is 4
num is 8
num is 16
num is 32
num is 64
num is 128
传递参数
def total(from, to)
result = 0
from.upto(to) {
|num|
if block_given?
result += yield num
else
result += num
end
}
result
end
puts total 1, 3
puts total(1,3) { # total后一定要紧跟括号
|num|
num ** 2
}
块本身也可以作为参数传递给函数(不实用yield方法)
# 块本身也可以作为参数传递给函数
def test(&block)
block.call
end
test {
puts 'Hello World!'
}
模块可以把方法、常量、模块组合在一起
被引用的模块文件support.rb
module Support
PI = 3.1415926
def Support.hello(name) # 模块中的普通函数用模块名开头区分
puts "hello #{name}"
end
end
module Week
FIRST_DAY = 'Sunday'
def Week.weeks_in_month
puts 'You have 4 weeks in a month'
end
def Week.weeks_in_year
puts 'You have 52 weeks in a year'
end
end
main.rb
$LOAD_PATH << '.' # 添加搜索路径目录
require 'support' # 添加具体模块
# 调用模块方法
Support::hello 'ruby'
# 读取模块函数
puts Support::PI
# 在类中引用模块内容要用include
class Decade
def initialize
@no_of_yrs = 10
end
# include Week
def no_of_months
puts Week::FIRST_DAY
number = @no_of_yrs * 12
puts number
end
end
d = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d.no_of_months
#运算结果
hello ruby
3.1415926
Sunday
You have 4 weeks in a month
You have 52 weeks in a year
Sunday
120
mixins实现多重继承
support.rb
module A
def a1
puts 'a1'
end
def a2
puts 'a2'
end
end
module B
def b1
puts 'b1'
end
def b2
puts 'b2'
end
end
main.rb
$LOAD_PATH << '.' # 添加搜索路径目录
require 'support' # 添加具体模块
class Sample
# 用 include方法把模块中的方法包含到类内
# 组装模块
include A
include B
def s
puts 's'
end
end
s = Sample.new
s.a1 # 调用模块中的方法
s.a2
s.b1
s.b2
s.s
以上就是Ruby语法基础(二)的详细内容,更多关于Ruby语法基础(二)的资料请关注九品源码其它相关文章!