模板 下面是一个针对int的冒泡排序 // _20180301.cpp : Defines the entry point for the console application. // #include "stdafx.h" void Sort(int* arr,int nLength) { int i,k; for (i = 0;ix > base.x && this->y > base.y; } private: int x; int y; }; template void Sort(T* arr,int nLength) { int i,k; for (i = 0;iy) return x; else return y; } M min() {……
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 old_hello hello def hello "new hello" end puts old_hello puts hello File Read/Write 文件读写 File.read File.readlines File#rewind etc IO.read/write File Read file = File.open("run.log", "r") while line = file.gets puts line end File Write file = File.open("run.log", "a+") file.puts "hello" file.close File.open("run.log", "a+") do……
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 = "world" puts user.name puts user.hello # module"s self module Management def self.track "track" end end class User include Management end # User.track # => error Management.track # class_eval in project # requirement: we need to execute a class method when module included module Manegement def self.included……
继承示例 # 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 = User.new("user_1", 18) p user.panels puts "-" * 30 admin = Admin.new("admin_1", 28) puts admin.name p admin.panels # 查看这个类的父类 p Admin.superclass 常用關鍵字 super关键字 调用父类的同名方法 self關鍵字 指向當前作用域實例 # inheritance class User attr_accessor :name, :age def initialize name,……
Everything is Object 一切皆对象 a = "hello" a.class # => String b = 3.14 b.class # => Float c = %w[pear cat horse] c.class # => Array Instance Method & Instance Attribute 实例方法,实例属性 Instance Method: 实例方法,成员方法,成员函数 Instance Attribute: 实例变量,成员属性,属性(property),使用@定义 # class class User def initialize name, age @name = name @age = age end # getter def name @name end def age @age end end user = User.new("Hello", 18) puts user.name puts user.age # class class User def initialize name, age @name = name @age = age end……