README

Ruby

常用部分集合

String

string length
    str.length
string 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 nil
string 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.new
t.methods.include? 'methodName'  # => TRUE
object.respond_to?(:'method')

對象的類型

"1".instance_of? String
object.is_a?(String)
object.respond_to?(:to_s)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章