Ruby
来源:互联网 发布:百度人工智能开发平台 编辑:程序博客网 时间:2024/06/14 22:38
常用部分集合
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 }数组拼接string: ['12','34','35','231'].join(",")
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)
文件操作
File.write('/path/to/file', 'Some glorious content')
循环 中断
continues 相当于 next
next
阅读全文
0 0
- ruby
- ruby
- ruby
- Ruby
- Ruby
- Ruby
- ruby
- ruby
- ruby
- Ruby
- RUBY
- ruby
- Ruby
- ruby
- Ruby
- ruby
- ruby
- Ruby
- android调用照相机拍照获取照片并…
- 有一个分数序列2/1+3/2+5/3+8/5+13/8+…求出这个数列前20项的和
- vijos 1083 小白的公园 线段树
- 分页查询概括
- 网易校招第6题(看到一份比较好的代码)
- Ruby
- 微信开发 本次测试环境搭建 JAVA开发
- 自动驾驶叉车(一)
- Swift 3 打印功能
- android中保存Bitmap图片到指定文件夹中的方法
- kruskal算法学习笔记(并查集做法)
- javaweb tomcat+jsp+servlet的一个简易登陆界面
- PAP与CHAP对比
- 国内maven使用地址