Ruby 的相关知识点

来源:互联网 发布:人民币玩家 知乎 编辑:程序博客网 时间:2024/05/22 01:27

Ruby 的相关知识点

ruby 的整体风格特征:

%q 单引号字符串(不解释嵌套表达式#{ … })

%q(string test #{time.now}) == 'string test #{time.now}'
%Q 双引号字符串(不解释嵌套表达式#{ … })
%(string test #{Time.now}) == "string test #{Time.now}"
%r 正则表达式模式
foo = "var"%r(/home/#{foo})  == %r(/home/#{foo})

%i 符号 symbol 数组

 %i(one two three) == [:a, :b, :c]

require, load,include 都是 Kernel 模块中的方法,他们的区别如下:

  • require,load 用于包含文件,include 则用于包含模块。
  • require 加载一次,load 可加载多次。
  • require 加载 Ruby 代码文件时可以不加后缀名,load 加载代码文件时必须加后缀名。
  • require 一般情况下用于加载库文件,而 load 用于加载配置文件。

ruby 标识符的一些约定:

  • 局部变量以小写字母或者下划线开头
  • 全局变量以美元符号$开头。
  • 实例变量以 at 符号@开头
  • 类变量以双 at 符号@@开头
  • 常量或类名或模块名以大写字母开头(建议常量全部用大写)。
  • 伪变量:truefalsenil__FILE__,__LINE__

Ruby 中的访问权限:

  • public公共方法,可以被定义它的类和其子类访问,可以被类和子类的实例对象调用;

  • protected保护方法,可以被定义它的类和其子类访问,不能被类和子类的实例对象直接调用,但是可以在类和子类中指定给实例对象;

  • private 私有方法,可以被定义它的类和其子类访问,私有方法不能指定对象

区间:

.. :两个点号创建一个闭区间

...:而三个点号创建一个右开区间(即右边界不取值

正则表达式:

  • Ruby 中正则表达式的写法
1.在/ ... /之间,要进行转义。2.在%r{ ... }内,不用进行转义。3.Regexp.new()内,不用进行转义。
  • 匹配的两种方法
=~ 肯定匹配, !~ 否定匹配。=~ 表达式返回匹配到的位置索引,失败返回 nil,符号左右内容可交换md = regexp.match(str),返回 MatchData 数组,从 0 开始,md[0]存储的是匹配到的值。 md.pre_match:返回匹配前内容($`)。md.post_match:返回匹配后内容($’)。例:p /cat/ =~ "dog and cat" #=> 8md = /cat/.match("bigcatcomes")puts "#{md.pre_match}->#{md[0]}<-#{md.post_match}"
  • 替换
sub(): 只替换第一次匹配gsub(): 会替换所有的匹配,没有匹配到返回原字符串的副本。str = "ABDADA"new_str = str.sub(/A/, "*")new_str2 = str.gsub(/A/, "*")p new_str #=> "*BDADA"p new_str2 #=> "*BD*D*"注意:1.如果想修改原始字符串用 sub!()和 gsub!(),没有匹配到返回 nil。2.方法后面还可以跟 block,对匹配的字符串进行操作例:    a='quick brown fox'        result=a.gsub(/[aeiou]/) do | v |        v.upcase     end    p result # => "qUIck brOwn fOx"
  • 分组匹配
Ruby 的分组匹配与其它语言差别不大,分组匹配表达式是对要进行分组的内容加()。 对于匹配到的结果,可以用系统变量#$1,#$2,...索引,也可用 matchData 数组来索引,索引值从 $1 开始。  md = /(\d\d):(\d\d)(..)/.match("12:50am")    puts "Hour is #$1, minute #$2"    puts "Hour is #{md[1]}, minute #{md[2]}"
  • 匹配所有

    match():只能匹配一次

    scan():匹配所有

    示例:

    result="abcabcabz".scan(%r{abc}) p result #=> ["abc", "abc"]result.each{|item|    puts item}               #=>输出 2 行 abcresult="abcabcabz".match(%r{abc}) p result[0]          #=> ["abc"]
  • 贪婪匹配 vs 懒惰匹配

    贪婪匹配:尽可能多匹配,正则默认是贪婪匹配

    a.*b 它将会匹配最长的以 a 开始,以 b 结束的字符串。 对于 aabab 的匹配结果是 aabab。 result="aabab".match(/a.*b/)p result[0] #=> "aabab"

    懒惰匹配:尽可能少匹配

    a.*?b 对于 aabab 的匹配结果是 aab 和 ab。result="aabab".scan(%r{a.*?b})p result #=> ["aab", "ab"]

Ruby 哈希 hash 表操作

  • hash 的定义

    lst={:key1 => value1,:key2 => value2, :key3 => value3,......}

    hash 的读取、赋值

    p lst[:key2]lst[:key4]='jack' p lst[:key4]

    hash 的键或值个数

    p lst.keys.sizep lst.keys.count p lst.values.size p lst.values.count

    hash 的遍历

    lst.each{ | key, value | puts "#{ key }=>#{ value }" }

Ruby 数组的操作

  • 创建一个Array对象

    Ruby 的数组自动增长,同时增加他们的元素。创建数组:有许多方法来创建或初始化数组。一种方法是用新的类方法:names = Array.new在创建阵列时,您可以设置一个数组的大小:names = Array.new(2) #=> [ nil, nil ]该数组 names 现在 2 个元素,值都为 nil。你可以返回一个数组的大小或长度的方法:months.size # This returns 2months.length # This also returns 2例:names = Array.new(4, "mac")puts "#{names}" #=> ["mac", "mac", "mac", "mac"] nums =     Array.new(10) { | e | e = e * 2 }puts "#{nums}" #=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] nums =   Array[1, 2, 3, 4,5]p nums #=> [1, 2, 3, 4, 5]digits = Array(0..9)puts "#{digits}" #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  array=Array[1,2,3,4,5]array << 6 << 7 << 8 #向数组中追加元素,或    array.push(6).push(7).push(8) parray #=>[1,2,3,4,5,6,7,8]array=%W(ab cd efg)parray.include?("ab") #=>truearray.each_with_index do | arr, index |p arrp index enda=[1,2,3,5,7,9]b=[2,4,6,8,10]#两数组相连(不去重)p(a+b) #=>[1,2,3,5,7,9,2,4,6,8,10]#a 数组中的元素减去 b 数组中与之相同的元素 p (a-b) #=> [1, 3, 5, 7, 9]    #(并集)除去两个数组中相同的元素p(a|b) #=>[1,2,3,5,7,9,4,6,8,10] #(交集)只有两个数组中都相同的元素     p(p&b)      #=>false
  • 创建一个 Array 对象的实例

    Array.[](...) 或 Array[...] 或 [...] 或 Array.new(n) { | x | x = 初始值 }1.数组的定义    array=[1,2,3,4,5,6] array=Array.[](1,2,3,4,5)       array=Array[1,2,3,4,5] i=1    Array.new(4) { | x | x += i}    p array #=> [1, 2, 3, 4, 5]2.数组的读取、赋值    p array[0] array[4]='jack' p array[4]3.数组的个数    p array.size    p array.count 4数组的遍历(index 从 0 开始计数)    array.each{ | item | puts item }     或     array.each_with_index{ | item,index |         puts “#{index}: #{item}”     } 

数组与hash

  • 数组与hash转化

        a = [1,2,3]    c = []    a.each do |itme|        c.push({key  => item})    end
  • 数组遍历合并

    a = [1,3,5]b = [2,4,6]a.each_with_index do |i,index|        if !b[index].nil?            re_array.push(i + "," + bg_lawyer[index])        else            re_array.push(i + "," + "null")        end    end

self

=begin    类定义:        class C            self  =>类对象self    模块定义:        Module M            self =>模块对象M    方法定义:        1.顶层(任何定义模块外)            def method_name                self => 方法被调用时,无论怎样对象都是self,顶层的方法作为私有的方法所有对象可用        2.类的实例方法:            class C                def method_name                    self => C 的一个实例,响应method_name        3.模块中的实例方法定义            moudle M            def method_name                self =>继承了M的实例对象/混合了M的类实例        4.特殊对象的单例方法            def Obj.method_name                self =>Obj =end#self在顶层是默认的默认对象mainputs "Top Level"puts "self if #{self}"#self 在类定中是类的本身class C    puts "Class definition block"    puts "self is #{self}"    def self.x        puts 'Class method C.x:'        puts "self is #{self}"    end    def m        puts "Instance mothod C#m:"        puts "self is #{self}"    endendC.xc = C.newc.m#在类和模块中通过调用puts测试selfclass C    puts "Just started class C:"    puts self                #=>C    module M        puts "Nested moudlue C::M"        puts self         #=>C::M    end    puts "Back in the outer level of C:"    puts self            #=>Cend#实例方法定义selfclass C    def x        puts "Class C, method X:"        puts self    endendc = C.newc.x#在单例方法和类方法定义中的selfobj = Object.newdef obj.show_me    puts "Inside singleton method show_me of #{self}"endobj.show_meputs "Back from call to show_me by #{self}"class C    def C.x        puts "Class method of class C"        puts "self: #{self}"    endendclass C    def C.no_dot        puts "As long as sekf is C ,you can this method with no dot"    end    no_dotendC.no_dotclass Person    attr_accessor :first_name, :middle_name, :last_name    def whole_name        n = first_name        n << "#{middle_name}" if middle_name        n << last_name    endenddavid = Person.newdavid.first_name = "david"david.last_name = "Black"puts "David's whole name: #{david.whole_name}" david.middle_name = "Alan"puts "David's new whole name:#{david.whole_name}"#通过self解析实例变量class C    def show_var        @v = "I am an instance vriable initialized to a string"        puts @v    end    puts @v = "Instance variable can appear anywhere..."endC.new.show_varclass C    puts "Just inside calss definition block.Here's self"    p self    @v = "I am an instance variable at the top level of a class body"    puts "Ande here's the instance variable @v, belonging to #{self}:"    p @v    def show_var        puts "inside an instance method definition block. Here's self"        p self        puts "And herer's the instance variable @v, belonging to #{self}"        puts @v    endendc = C.newc.show_var#重用嵌入在局部作用中的变量名class C    module M        module N            class D                def show_a                    a = 1                    puts a                end                puts 0            end            puts 2        end        puts 3    end     puts 4endd  = C::M::N::D.newd.show_a#局部作用域和self的相互作用#递归:演示每次方法调用时产生了新的局部作用域class C    def x(value_for_a, recurse=false)        a = value_for_a        print "Herer's the inspect-string for 'self':"        p self        puts "And here's a"        puts a         if recurse            puts "Calling myself (recursion).."            x("Second value for a")            puts "Back after recursion; here's a:"            puts a        end    endendc = C.newc.x("first value for a", true)#私有的setter (=) 方法
1 1