README

来源:互联网 发布:速读训练软件安卓版 编辑:程序博客网 时间:2024/06/01 17:45

Ruby

常用部分集合

String

string length    str.lengthstring substring    str[index] → new_str or nil click to toggle source    str[start, length] → new_str or nil    str[range] → new_str or nil    str[regexp] → new_str or nil    str[regexp, capture] → new_str or nil    str[match_str] → new_str or nilstring regex    str[fixnum] = new_str click to toggle source    str[fixnum, fixnum] = new_str    str[range] = aString    str[regexp] = new_str    str[regexp, fixnum] = new_str    str[regexp, name] = new_str    str[other_str] = new_str

Hash

初始化    grades = {}    grades = Hash.new    grades["Dorothy Doe"] = 9    options = { font_size: 10, font_family: "Arial" }转string     h.to_s包含key:    h.has_key?("a") 所有keys    h.keys 包含value    h.has_value?(100)所有values    h.values判断空:    {}.empty?   #=> true长度    h.length设置default:    h.default("1")删除key:    h.delete(key)删除条件    h.delete_if{| key, value | block }删除所有key:    h.clear反转 key=》 value --- to  --- value =》 key    h.invert遍历    h.each {|key, value| puts "#{key} is #{value}" }    h.each_key {|key| puts key }    h.each_value {|value| puts value }

Array

初始化:    ary = []    ary = Array.new(3)取元素    e = ary[1]    e = ary.first    e = ary[-1]长度    ary.length    ary.count空    ary.empty?包含?    ary.include?('Konqueror')添加到尾部    arr.push(5)添加到头部    arr.unshift(0)插入    arr.insert(3, 'apple') 一个,或多个    arr.insert(3, 'apple','apple2','apple3')删除    arr.pop 尾部删除    arr.shift 头部删除    arr.delete(index)删除数组中 nil 对象    arr.compact 生成新数组    arr.compact! 改变数组内容,还是 array删除重复对象    arr.uniq遍历    arr.each { |a| print a -= 10, " " } 正序遍历    reverse_each 倒叙遍历遍历的 map操作    arr.map { |a| 2*a } 不改变 arr 内容    arr.map! { |a| 2*a } 改变arr 内容遍历符合条件的对象集合    不会修改array    arr.select { |a| a > 3 }     arr.reject { |a| a < 3 }    arr.drop_while { |a| a < 4 }    修改array    arr.delete_if { |a| a < 4 }    arr.keep_if { |a| a < 4 }

object has function? 对象是否有某个方法

> Classes: TestClass.methods.include? 'methodName'  # => TRUE> Objects:t = TestClass.newt.methods.include? 'methodName'  # => TRUEobject.respond_to?(:'method')

对象的类型

"1".instance_of? Stringobject.is_a?(String)object.respond_to?(:to_s)
原创粉丝点击