Saturday, 8 October 2011

Note FOR Ruby 1.9 (1)

  1. Ruby之引号:
    • 单引号:不进行转义
    • 双引号:转义字符和嵌入表达式计算
    • `:作为system的命令执行
    • 自定义字符串分割符:
    • %Q/string/: 代表双引号字符串
      %/string/: 代表双引号字符串
      %q/string/: 代表单引号字符串
      %w/ / :单引号字符串Array
      %W/ / :双引号字符串Array
      %r| | : 正则表达式
      %s/ /: symbol
      %x/ /: 命令
      另外%Q(%q)后可以选择其他非字母数字字符,例如#, [, {
    puts 'sample #{1+1}\n'
    puts "sample #{1+1}\n"

    sample #{1+1}\n
    sample 2

  2. Ruby之注释:
  3.   有#和=begin/=end两种
  4. Ruby之变量:
    • var 局部变量
    • $var 全局变量
    • @var 类实例变量
    • @@var 类变量
    • Class::VAR 类常量
  5. Ruby之字符串:
    • 字符串连接:三种方式: << , + 或者空格隔开
    • 多行字符串:
    • <<LABEL
      LABEL

      <<'LABEL' 代表单引号字符串
      LABEL

  6. Ruby之main:
  7.   程序在运行时,Ruby会创建一个main对象 puts self
    puts self.class
    main
    Object
  8. Ruby之new, initialize, super:
  9. class People
        def initialize(name)
            @name = name
        end

        attr_reader :name
    end

    class Male < People
        def initialize(name)
            super
        end
    end

    class Female < People
        def initialize(name, beauty)
            super(name)
            @beauty = beauty
        end

        attr_reader :beauty
    end

    baron = Male.new('Baron')
    puts baron.name
  10. Ruby之inspect:
  11.   很好的调试工具
    puts baron.inspect OR p baron

    #<Male:0x1267e90 @name="Baron">
  12. Ruby之类实例属性访问:
    • 编写访问函数
    • def get_name
          return @name
      end

      def set_name(name)
          @name = name
      end
      baron.set_name 'PAN'
      puts baron.get_name
    • =号赋值
    • def name
          return @name
      end

      def name=(name)
          @name = name
      end

      baron.name = 'PAN'
      puts baron.name
    • reader和writer
    • attr_reader :name
      attr_writer :name
      OR attr_accessor :name
  13. Ruby之Object:
  14.   Ruby中所有类继承于Object,可以通过object_id查看实例id
    cls = baron.class
    begin
        cls = cls.superclass
        puts cls
    end until cls == nil

    People
    Object
    BasicObject

No comments :

Post a Comment