Agenda Loop Expression File Read/Write Debug Process & Thread Loop while
a = 10 while a > 0 puts a a -= 1 end until
a = 100 until a == 0 puts a a -= 1 end loop
a = 10 loop do break if a 0 !~ 正则匹配 是否匹配不到 匹配到返回fals 匹配不到返回true
/666/i !~ "hello world" # => true alias 别名
def hello "hello" end alias …
Agenda class_eval & instance_eval method_missing Module as a namespace Gems require vs load $LOAD_PATH class_eval 首先class_eval是只有类才能调用的,Class#class_eval class_eval会重新打开当前类的作用域 # class_eval class User end User.class_eval do attr_accessor :name def hello "hello" end end user = User.new user.name = …
继承示例 # inheritance class User attr_accessor :name, :age def initialize name, age @name, @age = name, age end def panels # ||= 操作符, 如果变量不存在 那么就赋值 @panels ||= ["Profile", "Products"] end end class Admin < User def panels @panels ||= ["Profile", "Products", "Manage Users", "System Setup"] end end user …
变量赋值 # 变量交换 a = 1 b = 2 b,a = a,b puts a puts b puts "-" * 30 x = [1, 2, 3] a, b = x #默认会把数组中的值依次赋值给 a ,b puts a puts b puts "-" * 30 x = [1, 2, 3] a, *b = x #这里a会接受第一个元素 b用了*号 表示接受剩下所有的元素 puts a p b #output 2 1 ------------------------------ 1 2 ------------------------------ 1 [2, 3] Fixnum & …
Block 代码块 Block是一个参数 匿名参数 Callback 使用do/en或者{}来定义 {puts "hello"} Demo:
# block usage def hello puts "hello method start" yield yield puts "hello method end" end hello {puts "i am in block"} #output hello method start i am in block i am in block hello method end # yield with parameter def hello puts …