Ruby小笔记

来源:互联网 发布:对数据库安全性的认识 编辑:程序博客网 时间:2024/06/13 05:08

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

    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\AStart of string\zEnd of string
    .Any single character\sAny whitespace character\SAny non-whitespace character\dAny digit\DAny non-digit\wAny word character (letter, number, underscore)\WAny non-word character\bAny word boundary character
    (...)Capture everything enclosed(a|b)a or ba?Zero or one of aa*Zero or more of aa+One or more of aa{3}Exactly 3 of aa{3,}3 or more of aa{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

     

 


0 0
原创粉丝点击