Ruby on Rails
学习笔记之三 -- Ruby 核心类
一、Array 1. 1) 2) 3) 2. 1) 2) 3) 4) 5) 3.
实例化 Array.new [值 1、值 2、值 3、值 4、值 5] %w[red green blue balck] 自动把字符串
列表转成数组, 可以省掉引号及逗号。
方法 empty? 返回 true 或 false size first last
返回大小
返回第一个
返回最后一个
delete “元素” 删除 技巧: 查看类帮助 输入命令 ri 类名 例 ri Array
二、Hash: 保存键值对 1. 1) 2) 2. 1) 2) 3) 4)
实例化 Hash.new {key => value, key => value}
方法 empty? size keys : 返回所有的 key values 返回所有的 value
三、String : 用单引号或双引号 1. 2. 3. 要在字符串里包括引号等特殊符号,需要进行转义 " 快捷方式:%Q(字符串) 例:%Q( Arnie said, “I’m back!” ) 在字符串里可以嵌入 Ruby 表达式 #{表达式} 例:“当前时间:#{Time.now}”
注意这边只能是双引号,单引号会把表达式原样输出 4.
方法
gsub(值 1,值 2), 把字符串里的值 1 替换成值 2 include?(值) 是否包含 slice(0,3) 截取 四、Numeric : Float Fixnum Bignum 1. 2. 3. 4. 5. 123.integer? 是否整数 12.3.round 8.zero? 12.to_f 11.3.to_i
四舍五入 是否为 0 转为 Float 转为 Fixnum
五、Symbol 符号 1. 2.
相当于字符串,但是没有任何的方法
相互转换 “fox”.to_sym :fox.to_s
Ruby 动态追加类定义
Ruby 是动态语言,允许随时更改类定义,如我们在定义一个类时,该类已经存在,则此时的定义 是对先前类的追加,而不是重新定义. class Apple def show puts "一个苹果"
end end a=Apple.new() a.show class Apple #为 Apple 类追加一个 test 方法 def test puts "口感不错" end end a=Apple.new() a.show a.test
使用特殊类定义为某个对像追加方法和变量. class << a def name puts "富士" end end a.show a.name 使用特殊类定义为 a 对象追加了个 name 方法后,a 就可以调用 name 方法,但其它的 Apple 实 例依然没有 name 方法.
Ruby 笔记-方法
更改已有对象 class String # 方法扩展 def test(*args) yield *args << self.to_i end # 方法缺失 def method_missing(method, *args, &;block) p "'#{self}' missing #{method} : #{args} #{block}" # 无限循环 → p "what is #{this}" block.call self end end
# 普通参数,和 do/end 代码块 fruit = 'apple' 'any'.foo 1,2,3 do p "#{fruit} alives" end # -> "apple alives" # 普通参数,和花括号代码块同时存在,需要一个括号 'a'.test(1,2,3) { |*x| p "callback results: #{x}" } # -> "callback results: [1, 2, 3, 0]" 额外的一点是,不能 method_missing 再调用一个缺失的方法。
像英文一样书写代码 # II 英文似的方法 animals_can_fly = ['angry birds','silly duck'] def let(animal,&;action) action.call animal end def fly(&;action) yield end def keep(state) p "keep #{state}" end let 'angry birds' do |animal| fly { keep "height at 8.88km" } if animals_can_fly.include? animal end # -> "keep height at 8.88km"
Ruby 实实在在地改变了代码风格! 像 objective-c 一样处理 nil 对象的消息 class NilClass def method_
missing(method, *args, &;block) p 'send a message to nil' end end person = nil person.laugh 'string'.foo # -> "send a message to nil" # -> "'string' missing foo : [] "
# -> "send a message to nil" Ruby 里面全部都是对象,包括 nil。 最 后 一 行 表 明 , 存 在 一 个 向 上 的 方 法 调 用 链 , String#method_missing -> NilClass#method_missing