字符操作 数组循环 异常
$ brew install ruby # 安装
$ irb
-
%
取余
-
<<
字符接入,如 a<<b 为 b 接到 a 末尾
-
*
字符循环
- 单引号字符原文输出
- 双引号字符转意输出
puts games.join(",") # 数组连接
if games.respond_to?("each") end # 判断是否为数组,或 respond_to?("each_with_index")
for game in gamelist do end # 循环
for num in 1..5 do end # 循环 1 到 5
for num in 1...5 do end # 循环 1 到 4
gamelist.each { |game| puts game }
gamelist.each do |game| puts game end
gamelist.each_with_index do |game,i| puts i.to_s + "." + game end
5.times do |i| # times 循环
puts "第 #{i+1} 次times循环"
end
1.step(10,3) do |i| # step 循环
puts "#{i}"
end
2.upto(5) do |i| # upto 循环
puts "updo=" + i.to_s
end
5.downto(2) do |i| # downto 循环
puts "downto=" + i.to_s
end
begin # 异常
raise "my raise error!"
rescue => e
puts e
else puts "正常处理"
ensure puts "扫尾处理"
end
类 模块
class Game
attr_accessor :price # 定义存储属性,调用 mario.title 报错
def initialize(title = "怪物猎人世界", price = 200)
@title = title @price = price
end
def show() puts "标题:#{@title}" puts "价格:#{@price}" end
def self.toStr puts "I love this game." end # 静态
end
puts Game.instance_methods(false) # 显示所有方法,false 为不显示父类方法
mario = Game.new("超级马里奥", 350)
if mario.respond_to?("show") # respond_to? 判断对象是否存在某方法,send 执行方法
mario.send("show")
end
class SteamGame < Game end # 继承
module BaseFunc
Version = "0.0.1" # 模块和类都正常调用
def v return Version end
def add(a, b) return a + b end # 模块不可调用
def self.showVersion return Version end # 类不可调用
module_function :v # 类不可调用
end
class BaseClass include BaseFunc end # 用模块创建类
网友评论