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)