ruby语法初记-1

ruby语法小记-1

 

一、数字
  1. Numeric为最上层类。子类有Integer,Float,Complex(复数),BigDecimal,Retional(有理数)
  2. ** 指数操作  如a**4 = a*a*a*a
  3. 7%3 = 1  ; -7%3 = 2  7%(-3) = -2 。(ruby中取模操作的结果的符号与第2个参数相同,不同于java;-a/b = a/(-b))
二、文本
  1. 单引号的字符串
  2. 双引号包含的字符串可以包含任意的ruby表达式。用#{}表达。 如 a = "pi is #{Math::PI}"  。当要插入的字符串字面量的表达式只是对于全局、实例或者变量的引用时,则{}可以省略,如$a = 'hello'  b = "#$a world" 。输出值为hello world。如果不需要计算,则在#前添加\转义,只要在#后面跟{,$,@时才需要这样做。
  3. HERE DOCUMENT。包含在<<某个标识或<<-某个标识) 和单独出现在一行的某个标识之间的所有文本。
  4. ruby的字符串是可变的,每当ruby遇见一个字符串字面量时,都会新建一个字符串对象。如下可以验证:10.times{ p  'pet'.object_id}
  5. 单个字符的快捷调用方式,?A = "A" = 'A'
  6. 弱类型s = 'hello'   s[1] = 'e'   s[0,2] = 'he'
  7. 迭代。ruby1.9中取消了对字符串的each方法,取而代之的是each_byte,each_char,each_line。s.each_char{|x| p x}的迭代方式比0.upto(s.size-1){|x| p s[x]}更加高效
  8. Encoding类,字符集。 方法:to_s,name,inspect,list.工厂方法 Encoding.find("utf-8")
三、数组
  1. size,length,0..size-1,没有数组越界,简单返回nil
  2. ruby数组是无类型且可变的,数组元素不必属于同一类型
  3. words = %w[this is a bird]   
    words = %w|thisi is a bird|     
    words = %w(this is a bird)                 
    # same as : ['this','is','a','bird'];  
        
  4. empty = Array.new
    nils = Array.new(3)
    zeros = Array.new(4,0)   #[0,0,0,0]
    copy = Array.new(arr) 
    count = Array.new(3){|x| x+1} #[1,2,3]
     5.('a','b').to_a, 数组迭代 arr.each{|x| p x}