- Ruby实现类继承
class Game
def initialize(id=1,title ="MeetDurian",price = 0)
@title = title
@price = price
end
def show()
puts "游戏名字: #{@title}"
puts "价格: #{@price}"
end
def otherShow()
end
def self.method
puts "静态方法,不能被实例化的调用"
end
end
class OtherGame < Game #Ruby通过 < 实现继承。
def otherInfo
puts “其他信息”
end
end
OtherGame.method
newGame = Game.new("2","MeetDurian2",300)
newGame.show
newGame.otherInfo
- 模块
类似于Class类但又不类似
module BaseV
version = "0.1"
def v
return version
end
def add(a,b)
return a+b
end
def self.showVersion
return version
end
#将v方法定义范围静态方法
module_function :v
end
puts BaseV::version #直接输出
puts BaseV.showVersion #引用自方法
puts BaseV::showVersion #同上
puts BaseV.v #同上
puts BaseV.add(1,2) #没有将add(1,2)实例化以及静态,因此不能使用
#include表示引用
class BaseV2 include BaseV
end
puts BaseV2::version #可以使用
puts BaseV2.showVersion #静态方法不能使用
puts BaseV2.v #静态方法不能使用
puts BaseV2.add(1,2) #不能使用,只有实例化才能使用
example = BaseV2.new
puts example.add(1,2) #结果为3
- 条件判断(重点)
if 、elsif 、unless(只要不,相当于 ! if )、case、when (注意elsif很特别)
a = 10
if a >=30
puts "a niubi"
elsif a >=20
puts "a >= 20"
else
puts "a < 20"
end
——————————
unless a < 9
puts "意思当判断为假的时候才打印这个,一般不要用unless"
else
puts "会输出这个,a>9"
end
today = o
case tody
when 0,7
puts"星期日"
when 1
puts"星期一"
when 2
puts"星期二"
when 3
puts"星期三"
when 四
puts"星期四"
when 5
puts"星期五"
when 6
puts"星期六"
else
raise Exception.new("输入错误")
- 循环
for、while、until
#示例一
lists = ["1","2","3"]
for list in lists do #python里面是将do换成:
puts list
end
#others:
for num in 1..5 do #循环 1 到 5
for num in 1...5 do #循环 1 到 4
while
#示例二
index = 0
while index < 5 do
puts "在这里:"+index.to_s #前面有解释
index+=1
end
until
#示例三
index = 0
until index == 5 do
puts "在这里:"+index.to_s #前面有解释
index+=1
end
其他循环:each、times、step、upto、downto
#接示例一
lists.each{ |list|
put list
}
lists.each do |list|
put list
end
lists.each_with_index do |list,i|
put list+ i.to_s
end
5.times do |i| #等于for(i=0;i<5;i++)
puts "第#{i+1}次times循环"
end
#step
1.step(10,3) do |i| #从1开始,每隔3个,循环到10
put "#{i}"
end
#upto
2.upto(5) do |i|
puts i
end
#downto
5.downto(2) do |i|
puts i
end
- 例外处理???
begin、rescue/else/ensure、end
begin #类似于java的try{}
#有可能发生错误的处理
puts ">处理开始"
#10/0
rescue => e #类似于java的catch(Exception ex){}
puts "错误发生!"
puts e
else #java没有
#正常处理
ensure
#无论是否发生错误,都可以走这一步,类似于finally{}