发布新日志

  • ruby笔记

    2011-11-02 09:03:36

    #puts "hello world!"
    #::
    =begin
    module
    class
    def,undef
    defined?
    if,then,else,elsif,case,when,unless
    for,in,while,until,next,break,do,redo,
    retry,yield
    not,and,or
    true,false,nil
    rescue,ensure
    super,self
    begin/end
    BENGIN END
    _FILE_,_LINE_
    return
    alias
    require,include

    [] []=
    **
    !~+-
    */%
    +-
    >> <<
    <= < > >=
    <=> == ===
    =~ != !~
    &&
    ||
    .. ...
    defined?
    not
    or and
    if unless while until
    begin/end
    局部变量、方法参数、方法名用一个小写字母开头
    或者用一个下划线开头,全局变量用美元符号作为前缀
    ¥,实例变量用@开头,类变量用@@开头
    类名、模块名、常量用大写字母开头。

    词首字母后面可以是字母、数字和下划线的任意组合
    @后面不可以直接跟数字


    类库

    require include将类库程序名包含在已经定义好的
    类、方法。从父类继承得到的方法可以直接使用

    I/O 输入/输出 Ruby语言Kernel模块的方法,Mix-in在根类的Object中


    puts带换行符号,print不带换行符号
    printf "Number:%4.3f,string:%s",7.8,"hi!" \n

    gets

    =end


    =begin
    数据类型

    浮点型数据小数点后必须跟数字1.1e3
    0表示八进制,0x表示十六进制,0b表示二进制

    字符串是在单引号,双引号之间的代码

    1..5    1,2,3,4,5 [1,5]
    1...5   1,2,3,4   [1,5)


        
    a =1;b=2+3
    a,b=b,a#值互换
    print a ; print b


    x=0
    a,b,c=x,(x+1),(x+2)
    puts a,b,c
    print a,b,c
    print a


    a=1;b=1.0;print a==b

    a=1;b=1.0;
    puts a.eql?(b)

    a=1;b=1.0;
    print a.equal?(b)


    a=1.0;b=a
    print a.equal?(b)


    puts 'aab'<=>'acb'
    puts     [5]<=>[4,9]



    puts (0..9)===3.14
    puts ('a'..'c')==='c'
    =~用来比较是否符合一个正则表达式,返回模式在字符串中被匹配到得位置,否则返回nil
    !~断言不符合一个正则表达式,返回true,false


    if 条件 then 语句 end
    语句 if 条件

    if conditon
        statement
        elsif condition
            statement
            else
                statement
            end
           

    unless= if not
       
        case object
            when condition
            statement
            when condition
            statement
            else
                statement
            end
           



    x=3
    case x
        when 1..2
        print "x=",x,";在1..2中"
        when 4..9,0
        print "x=",x,";在4..9中,或是0"
        else
            print "x=",x,";其它可能"
        end
       


    a =1
    until a>=10
    print a," "
    a=a+1
    end


    a=1
    while  not a>=10
        print a," "
    a=a+1
    end



    until= while not   
     

    for i  in 1..9
        print i, " "
    end

    break
    next
    redo
    retry



    puts "演示break"
    c='a'
    for i in 1..4
        if i==2 and c=='a'
            print "\n"
            break
        end
        print i,c," "
    end
    puts "\n\n"




    puts "演示break"
    c='a'
    for i in 1..4
        if i==2 and c=='a'
            c='b'
            print "\n"
            next
        end
        print i,c," "
    end
    puts "\n\n"



    puts "演示break"
    c='a'
    for i in 1..4
        if i==2 and c=='a'
            c='b'
            print "\n"
            redo
        end
        print i,c," "
    end
    puts "\n\n"



    puts "演示break"
    c='a'
    for i in 1..4
        if i==2 and c=='a'
            c='b'
            print "\n"
            retry
        end
        print i,c," "
    end
    puts "\n\n"


    for i in 2..100
        f=true
        for p in 2..i
            if i%p==0 and i!=p
                f=!f
                break
            end
        end
        print i," " if f
    end




    #3.times {print "Hi!"}
    #9.downto(1) {|i| print i if i <7}
    #1..9).each {|i| print i if i<7}
    #1.upto(9) {|i| print i if i<7}

    #0.step(11,3) {|i| print i}

    try catch finally throw
    begin/end rescue ensure raise



    谁将被影响 ====来编写代码
    以类为模块,以消息来驱动程序的执行


    对象===静态的属性 , 动态的方法
    子类型从父类型得到属性、方法。我们称之为继承

    同一个父类,不同子类有不同的行为和状态,我们称之为多态

    对象的属性、方法只有定义代码的人知道,其它的类不知道,这就是封装

    封装、继承、多态是面向对象编程的三个本质特征



    人们可以决定代码世界中一类事物的属性、方法,当然可以修改代码世界中
    一类事物的属性、方法,而且可以委托其它的类来修改,甚至删除。这就是动态
    动态语言超越静态语言之处,由于代码是一直运行着的,与其他代码一直交互,修改,删除应慎重,避免产生副作用。




    attr_writer:motherland

    def motherland=(value)
        return @motherland=value
    end




    attr_reader:motherland
    def motherland
        return @motherland
    end

    封装完成了 隐藏实现

    class Person
        def initialize(name,age=18)
            @name =name
            @age=age
            @motherland="China"
        end
        def talk
            puts "my name is "+@name+",age is "+@age.to_s
            if @motherland=="China"
                puts "I am a Chinese"
                else               
                puts "I am a foreigner"
            end
        end
        attr_writer:motherland
    end

    #p1=Person.new("kaichun",20)
    #p1.talk
    #p2=Person.new("Ben")
    #p2.motherland ="ABC"
    #p2.talk
               

    puts "****************"

    class Student < Person
        def talk
            puts "I am a student. my name is "+@name+", age is "+@age.to_s
        end
    end
    p3=Student.new("kaichuan",25);p3.talk
    p4=Student.new("Ben"); p4.talk
           
       
       
    继承、重写方法
    子类继承父类可以重写方法、也可以增加一些新的方法,以增强父类的方法

    当你new的时候,一个实例就按照蓝图生成了






    Ruby灵巧、快速,但并不简单!
    冗余,不可预知
    冗余性、缺陷性、动态性


    由编译内核(或解释内核)在运行时刻来判断变量类型的语言,叫动态语言

    一切都是对象,但是变量不是对象,变量是引用某个对象时候的代号而已




    a=5
    b="hh"
    puts "a=#{5}"
    puts "b=#{b}"



    变量类型
    常量


    变量名、变量值、变量类型、变量的作用域



    (1..9).each {|i| print i if i<7}


    def one_block
        yield
        yield
        yield
    end
    one_block{puts "This is a block. "}



    def one_block
        for num in 1..3
            yield(num)
        end
    end
    one_block do |i|
        puts "This is block#{i}."
    end


    def do_something
        yield
    end

    do_something do
        (1..9).each {|i| print i if i<5}
        puts
    end

    do_something do
        3.times {print "Hi!"}
        puts
    end



    class Array
        def one_by_one
            for i in 0..size
                yield(self[i])
            end
            puts
        end
    end

    arr=[1,3,5,7,9]
    arr.one_by_one {|k| print k, ","}
    arr.one_by_one {|h| print h*h, ", "}

    class Array
    def one_by_one
    for i in 0...size
    yield(self[i] )
    end
    puts
    end
    end
    arr = [1,3,5,7,9]
    arr.one_by_one {|k| print k , ", "} # 1, 3, 5, 7, 9,
    arr.one_by_one {|h| print h*h, ", "} # 1, 9, 25, 49, 81,



    class Array
        def one_by_one
            for i in 0...size
                yield(self[i])
            end
            puts
        end
    end
    arr=[1,3,5,7,9]
    arr.one_by_one {|k| print k, ","}
    arr.one_by_one {|h| print h*h,","}


    def method(pr)
        puts pr.call(7)
    end

    oneProc=proc {|k|  k *=3}
    method(oneProc)





    def method(n)
        return proc {|i| n +=i}
    end

    oneProc=method(3)


    puts oneProc.call(9)
    puts oneProc.call(5)




    puts self.private_methods.sort




    rice_on_square =1
    64.times do |square|
        puts "On square #{square+1} are #{raice_on_square} gain(s)"
        rice_on_quare *=2
    end


    rice_on_square = 1
    64.times do |square|
    puts "On square #{square + 1} are #{rice_on_square} grain(s)"
    rice_on_square *= 2
    end



    rice_on_square = 1
    64.times {|square|
    puts "On square #{square } are #{rice_on_square} grain(s)"
    rice_on_square *= 2}

    #do end 替代{}
    #相当是一个循环!


    watir已经搭建好了!
    require "watir" 
    test_site = "http://www.google.com" 

    ie = Watir::IE.new 
    puts "Beginning of test: Google search." 
    #puts " Step 1: go to the test site: " + test_site 
    ie.goto test_site 

    ie.text_field(:name, "q").set "pickaxe"
    ie.button(:name, "btnG").click

    if ie.text.include? "Programming Ruby"  
    puts "  Test Passed. Found the test string: 'Programming Ruby'. Actual Results match Expected Results." 
    else 
    puts "  Test Failed! Could not find: 'Programming Ruby'." 
    end 
    puts "End of test: Google search."
    =end
  • Simple examples

    2010-10-17 21:17:25

    Let's write a function to compute factorials. The mathematical definition of n factorial
    is:
    n! = 1                (when n==0)
       = n * (n-1)!       (otherwise)

    Run in SciTE editor

    def fact(n)
      if n == 0
        1
      else
        n * fact(n-1)
      end
    end

    puts fact(5)


    Run in command line CMD
    see attachment


    #Program to find the factorial of number
    # Save this as fact.rb
    def fact(n)
     if n==0
      1
     else
      n*fact(n-1)
     end
    end
    puts fact(ARGV[0].to_i)
    #Here, ARGV is an array which contains the command line arguments, and to_i converts a character string to an integer.

    When you invoke ruby with no arguments,it reads commands from standard input and
    executes then after the end of input:
    ruby
    puts "hello world"
    puts "good-bye world"
    ^D

    The ^D above means control-D, a conventional way to signal end-of-input in a Unix context.

    ruby
    puts "hello world"
    puts "good-bye world"
    ^Z

    In DOS/Windows, try pressing F6 or ^Z instead.

  • ruby的命令行选项

    2010-10-17 13:47:34

    Run>CMD>CD ruby>ruby -h


    C:\ruby>ruby -h
    Usage: ruby [switches] [--] [programfile] [arguments]
      -0[octal]       specify record separator (\0, if no argument)
      -a              autosplit mode with -n or -p (splits $_ into $F)
      -c              check syntax only
      -Cdirectory     cd to directory, before executing your script
      -d              set debugging flags (set $DEBUG to true)
      -e 'command'    one line of script. Several -e's allowed. Omit [programfile]
      -Fpattern       split() pattern for autosplit (-a)
      -i[extension]   edit ARGV files in place (make backup if extension supplied)
      -Idirectory     specify $LOAD_PATH directory (may be used more than once)
      -Kkcode         specifies KANJI (Japanese) code-set
      -l              enable line ending processing
      -n              assume 'while gets(); ... end' loop around your script
      -p              assume loop like -n but print line also like sed
      -rlibrary       require the library, before executing your script
      -s              enable some switch parsing for switches after script. name
      -S              look for the script. using PATH environment variable
      -T[level]       turn on tainting checks
      -v              print version number, then turn on verbose mode
      -w              turn warnings on for your script
      -W[level]       set warning level; 0=silence, 1=medium, 2=verbose (default)
      -x[directory]   strip off text before #!ruby line and perhaps cd to directory
      --copyright     print the copyright
      --version       print the version

    请使用如下命令行启动Ruby解释器.

    ruby [ option ...] [ -- ] [ programfile ] [ argument ...]

    这里的"option"指下文将要提到的命令行选项中的一个。"--"则显式地表明选项字符串到此结束。"programfile"是装载Ruby脚本的文件。若省略不写或者写成"-"时,Ruby会把标准输入当做Ruby脚本进行处理。

    programfile若以“#!”开始,则进行特殊的处理。详细情况请参考下文的关于解释器行。

    argument中的字符串将变成内部常数ARGV的初始值。在有的环境中(Win32),标准shell不会展开通配符,这时Ruby解释器将自行展开通配符然后赋值给ARGV。此时,可使用的通配符有“*”、“?”、“[]”和“**/”(与Dir.glob不同,这里不能使用“{..}”)。在Win32环境中,若不想展开通配符的话,请使用单引号(')将参数括起来。

    命令行选项

    Ruby解释器可接受下列命令行选项。基本上与Perl的类似。

    -0数字

    以8进制数指定输入记录分隔符('$/')。

    若不指定数字的话,分隔符是空字符(等同于$/="\0")。数字后面可以有其他的开关(switch)。

    -00代表段落模式(等同于$/=""),-0777(因为这个代码不代表任何文字)表示将文件的全部内容一次性读入(相当于$/=nil)。

    -a

    与'-n'或'-p'一起使用时,可以打开自动拆分模式(auto split mode)。自动拆分模式将在各个循环前执行以下动作。

    $F = $_.split

    若没有同时指定'-n'或'-p'选项的话将不起作用。

    -C directory

    执行脚本之前,先移动到指定目录。

    -c

    只对脚本进行编译,而并不执行。编译后若没发现语法错误,则显示“Syntax OK”。

    --copyright

    显示版权信息。

    -Kc

    指定Ruby要处理的汉字编码。若是'E'或'e',则Ruby认定字符串或访问文件中的汉字编码为EUC。同样,若是'S'或's'的话则认定为SJIS。若是'U'或'u'则当作UTF-8处理。'N'表示不对汉字进行处理。该选项的默认值就是N(NONE)。

    将来有可能会改变文字编码处理方式,届时该选项的内容也会有所变化。

    -d --debug

    以调试模式执行脚本。将$DEBUG设置成true。

    -e script.

    在命令行中指定脚本。添加-e选项后,就不会从参数中抽取脚本文件名了。

    若多次使用-e选项时,系统会按照以下方式处理。

    下列各表达式的意义相同。 ruby -e "5.times do |i|" -e "puts i" -e "end" ruby -e "5.times do |i| puts i end" ruby -e "5.times do |i|; puts i; end" -Fregexp

    将regexp指定给输入域分隔符(field separator)。

    -h --help

    显示命令行选项的简介。

    -i[extension]

    对参数中指定的文件内容进行替换(in-place edit)。原始文件将被加上扩展名并保存下来。若没有扩展名的话,将不会进行备份,而且只有替换后的文件会被保留下来。

    例:

    % echo matz > /tmp/junk % cat /tmp/junk matz % ruby -p -i.bak -e '$_.upcase!' /tmp/junk % cat /tmp/junk MATZ % cat /tmp/junk.bak matz -I directory

    指定(追加)加载文件的路径。指定的目录将被追加到Ruby的数组变量($:)中。

    -l

    进行行尾自动处理。首先,将$\改为$/的值,在print输出时添加换行。若使用了-n标志或-p标志的话,将对gets读入的各行末尾进行String#chop!处理。

    -n

    若使用了该标志,则整个程序会像sed -n或awk一样,被

    while gets ... end

    括起来运行。

    -p

    与-n标志相仿,在各循环后输出变量$_的值。

    例:

    % echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"' MATZ -r feature

    执行脚本前,先对feature指定的库执行require操作。与'-n'选项、'-p'选项一起使用时特别奏效。

    -s

    对跟在脚本名后并且以'-'开头的参数进行解释,并将其值赋值给同名的全局变量。遇到以'--'开头的参数就停止解释,并将该参数从ARGV中删除。

    例:

    #! /usr/local/bin/ruby -s # prints "true" if invoked with `-xyz' switch. print "true\n" if $xyz -S

    该选项表明,当脚本名不是以'/'开头的时候,要使用环境变量PATH的值搜索脚本。若您的机器不支持#!的话,可以使用下列方法模拟#!的运行:

    #!/bin/sh exec ruby -S -x $0 "$@" #! ruby

    因为第1行的关系,系统把脚本交给/bin/sh。/bin/sh执行第2行后启动Ruby解释器。在-x选项的作用下,Ruby解释器把从'#!'到包含'ruby'的行的内容全部读入。

    根据系统的不同,$0未必包含完整路径,因此有必要使用'-S'选项来告诉Ruby在必要时搜索脚本。

    -T[level]

    执行不纯度测试。若给level指定了一个值之后,安全等级也会使用这个值。省略level时,其值为1。对于CGI程序来说,将其指定为-T1比较合适。$SAFE的等级也将被设定。

    -v --verbose

    冗长模式。启动时显示版本信息,然后将内部变量$VERBOSE设为true。当此变量为true时,众多的方法在运行时会显示冗长的信息。若只设定'-v'选项,而没有其他参数时,启动后会先显示版本信息,然后就结束运行(不会等待来自标准输入的脚本)。

    --version

    显示Ruby的版本信息。

    -w

    不显示版本信息的冗长模式。

    -W[level]

    ruby 1.8 特性

    可以指定3种级别的冗长模式,如下所示。

    -W0: 不显示警告 -W1: 只显示重要警告(默认) -W2 or -W: 显示所有警告

    内部变量$VERBOSE被分别设置为nil,false,true。

    -x[directory]

    从message中取出脚本并执行。读入脚本的范围是从'#!'开始,直到包含'ruby'的行为止。用EOF(文件结束),^D(controlD),^Z(controlZ)或保留字_END_来指定脚本结束。

    若指定了目录名的话,则在执行脚本前移动到该指定目录。

    -y --yydebug

    编译器调试模式。编译脚本时显示语法分析的过程。该显示过程会很漫长,可能只对那些想调试编译器的人有用。

    关于解释器行

    命令行指定的脚本是以'#!'开头的文件,当该行中不包含'ruby'时,将替代OS把'#!'后面的字符串看成命令行,然后启动解释器。

    例如,用Ruby运行下面的shell脚本时将启动sh。

    #!/bin/sh -vx echo "$@"

    若此行中包含'ruby'的话,则'ruby'左侧的部分将被忽略,右侧以'-'开头的部分被视为选项。

    这里指定的选项将被追加到以命令行方式指定的选项之中。这主要是为了嵌入那些本该在脚本中指定的选项。例如,下面脚本的作用等价于使用命令行方式指定-Ke选项。

    #! ruby -Ke

  • What is ruby?

    2010-10-17 13:47:34

    Ruby is "an interpreted scripting language for quick and easy objected-oriented programming"--what does this mean?

    Ruby
    interpreted scripting language
    1. ability to make operating system calls directly
    2. powerful string operations and regular expressions
    3. immediate feedback during development

    quick and easy
    1. variable declarations are unnecessary
    2. variables are not typed
    3. syntax is simple and consistent
    4. memory management is automatic

    object oriented programming
    1. everything is an object
    2. class,method,inheritance,etc.
    3. singleton methods
    4. "mixin" functionality by module
    5. iterations and closures

    also
    1. multiple precision integers
    2. convient exception processing
    3. dynamic loading
    4. threading support

Open Toolbar