Ruby小笔记,持续补充

  • 逻辑或运算符作用,判断空值的语法糖

    a=nil

    a||=333  则 a=333

     

  • inject的语法糖

    inject(initial, sym) → obj inject(sym) → obj inject(initial) {| memo, obj | block } → obj inject {| memo, obj | block } 

    例如  (5..10).inject(1,:+) 与 (5..10).inject(1) {|sum,n| sum+n}


  •  ruby gem 不下载rdoc ri

    vim ~/.gemrc

    gem: --no-ri --no-rdoc

     

  • ruby的正则表达式

        http://rubular.com/
    [abc] A single character: a, b or c
    [^abc] Any single character but a, b, or c
    [a-z] Any single character in the range a-z
    [a-zA-Z] Any single character in the range a-z or A-Z
    ^ Start of line
    $ End of line
    \A Start of string
    \z End of string
    . Any single character
    \s Any whitespace character
    \S Any non-whitespace character
    \d Any digit
    \D Any non-digit
    \w Any word character (letter, number, underscore)
    \W Any non-word character
    \b Any word boundary character
    (...) Capture everything enclosed
    (a|b) a or b
    a? Zero or one of a
    a* Zero or more of a
    a+ One or more of a
    a{3} Exactly 3 of a
    a{3,} 3 or more of a
    a{3,6} Between 3 and 6 of a

     

  •  类似awk的文本处理,命令行方式
            awk参考 http://www.cnblogs.com/chengmo/archive/2010/10/06/1844818.html 和 man awk
            cat /etc/passwd |awk -F: '/root/{print $1}' 
            或者
            awk -F: '/root/{print $1}' /etc/passwd

            ruby实现
            cat /etc/passwd |grep root |ruby -F: -ane 'puts $F[0]'

            注意要使用$类预定义变量,用双引号的时候,需要使用#{$_}计算变量值 
             cat /etc/passwd |grep root|ruby -ne 'a=$_.match(/\d+/);puts "#{$.} #{a} #{$_}" '

  • Rubygem出现“too many connection resets ”错误

          gem install 出现:删除用户目录下的.gem目录,以及gem的各种cache

          push gem 出现:http://help.rubygems.org/discussions/problems/715-too-many-connection-resets

 

  • Ruby正则表达式一特殊语法

             a = "hello there"

            a[/[aeiou](.)\1/, 1] #=> "l"

  • *的匹配

    一般来说*用于把一个array展开: 

      a, *b = [1,2,3]  #a = 1, b = [2,3]  

     引用 http://www.iteye.com/topic/24642

     

 

 

 




你可能感兴趣的:(Ruby)