ruby学习笔记(2)

2.1 变量的范围和分类
    1).Global scope variables
           全局变量以$开头
    2).Built-in global variables
           $0 ---表示当前运行文件名称
           $: --- 表示运行程序时寻找的库路径(类比classpath)
           $$ ---表示Ruby Process ID
    3).Local scope variables       
        (1)方法内的变量(def)
        (2)类内部的变量(class,module)
        (3)不在任何definition block内的变量
                 
       
2.2 Getting Input      
    使用gets获得键盘输入, 例:
   puts "In which city do you stay?" 
    STDOUT.flush         #flushes buffered data
    city 
= gets.chomp    #chomp remove '/n'
    puts 
"The city is " + city 

   
2.3 Ruby Names    
    1)Variables
        local variable name consists of lowercase letter or _ followed by name characters(sunil, _z, hit_and_run)
        instance variable name starts with an ''at'' sign (''@'')followed by an upper- or lowercase letter(@sign, @_, @Counter)
        A class variable  name starts with two signs (''@@'') followed by an upper or lowercase letter(@@sign, @@_, @@Counter)
        Global variables start with a dollar sign (''$'') followed by name characters.($counter, $COUNTER, $-x).   

    2) Constants
        A constant name starts with an uppercase letter followed by (lower) name characters   
        注意:类名称和module名称遵循Constants的命名规范
       
    3) Method Names   
        Method names should begin with a lowercase letter (or an underscore).
         注意:(1) 对于方法或变量名称,Ruby convention用_作为分隔符
                     (2) 对于类名或者模块名,Ruby convention用大写字母作为分隔符   
2.4 More on Ruby Methods
      ruby中的任何方法都必须由对象来执行,那么对于
puts, gets呢?
         we've always been inside a special object (main) Ruby has created for us that represents the whole program. You can always see what object you are in (current object) by using the special variable self.

2.5 Writing own Ruby methods
 Writing own Ruby methods
    1) ruby中的方法定义
       def fun  
        end
      注意:
        (1) 形参可用()声明
              def fun(name)
                  puts name
              end
      (2)  也可以不带括号,直接声明
            def fun name
                 puts name
              end   
    2) #(interpolation operator)符号的使用
        (1)指定函数的默认值
          def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank") 
              "#{arg1}, #{arg2}, #{arg3}."  #
          end 
          puts mtd  #结果为 Dibya, Shashank,Shashank
          puts mtd("ruby") #结果为 ruby, Shashank,Shashank
               
        (2)作为直接执行符号
           如 puts "100*5=#{100 * 5}"  #结果为100*5=500
       
    3) 设定函数别名
        def oldmtd
            "old method" 
        end 
        alias newmtd oldmtd  #设定函数别名
        def oldmtd 
            "old improved method" 
        end 
        puts oldmtd  #结果为old improved method
        puts newmtd  #结果为old method

    4) 接受数组作为形参
        def foo(*my_string) 
          my_string.each do |words| 
            puts words 
          end 
        end 
        foo('hello','world')  #结果为hello \n  world



2.6 清晰、精辟的总结
    * Avoid using Global scope and Global Variables. Global scope means scope that covers the entire program. Global variables are distinguished by starting with a dollar-sign ($) character. The Ruby interpreter starts up with a fairly large number of global variables already initialized.
    
* gets (get a string) and chomp (a string method) are used to accept input from a user.
    
* gets returns a string and a '\n' character, while chomp removes this '\n'.
    
* STDOUT is a global constant which is the actual standard output stream for the program. flush flushes any buffered data within io to the underlying operating system.
    
* To format the output to say 2 decimal places, we can use the Kernel's format method.
    * Ruby Names are used to refer to constants, variables, methods, classes, and modules. The first character of a name helps Ruby to distinguish its intended use.
    
* Lowercase letter means the characters ''a'' though ''z'', as well as ''_'', the underscore. Uppercase letter means ''A'' though ''Z,'' and digit means ''0'' through ''9.''
    
* A name is an uppercase letter, lowercase letter, or an underscore, followed by Name characters: This is any combination of upper- and lowercase letters, underscore and digits.
    
* You can use variables in your Ruby programs without any declarations. Variable name itself denotes its scope (local, global, instance, etc.).
    
* REMEMBER the way local, instance, class and global variables, constants and method names are declared.
    
* ''?'' and ''!'' are the only weird characters allowed as method name suffixes.
    
* The Ruby convention is to use underscores to separate words in a multiword method or variable name. For Class names, module names and constants the convention is to use capitalization, rather than underscores, to distinguish the start of words within the name. Examples: my_variable, MyModule, MyClass, MyConstant.
    
* Any given variable can at different times hold references to objects of many different types.
    
* Variables in Ruby act as "references" to objects, which undergo automatic garbage collection.
    
* For the time being, remember that Ruby is dynamically typed and that in Ruby, everything you manipulate is an object and the results of those manipulations are themselves objects.
    
* The basic types in Ruby are Numeric (subtypes include Fixnum, Integer, and Float), String, Array, Hash, Object, Symbol, Range, and RegEx.
    
* For the time being, remember that you can always see what object you are in (current object) by using the special variable self.
    
* We use def and end to declare a method. Parameters are simply a list of local variable names in parentheses.
    
* We do not declare the return type; a method returns the value of the last line.
    
* It is recommended that you leave a single blank line between each method definition.
    
* As per the Ruby convention, methods need parenthesis around their parameters.
    
* Methods that act as queries are often named with a trailing ?
    
* Methods that are "dangerous," or modify the receiver, might be named with a trailing ! (Bang methods)
    
* Ruby lets you specify default values for a method's arguments-values that will be used if the caller doesn't pass them explicitly. You do this using the assignment operator.
    
* For now remember that there is an interpolation operator #{}
    
* alias creates a new name that refers to an existing method. When a method is aliased, the new name refers to a copy of the original method's body. If the method is subsequently redefined, the aliased name will still invoke the original implementation.
    * In Ruby, we can write methods that can accept variable number of parameters.
    
* There's no limit to the number of parameters one can pass to a method.
    * The sequence in which the parameters are put on to the stack are left to right.
    
* Whether Ruby passes parameters by value or reference is very debatable - it does not matter.


posted on 2007-10-10 18:22 想飞就飞 阅读(2181) 评论(2)  编辑  收藏 所属分类: ROR

评论

# re: ruby学习笔记(2) 2007-10-10 20:12 彭俊

呵呵,继续,挺好  回复  更多评论   

# re: ruby学习笔记(2) 2009-04-07 13:49 coolfish

赞,力顶!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

公告


导航

<2007年10月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

常用链接

留言簿(13)

我参与的团队

随笔分类(69)

随笔档案(68)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜