• ruby语法


    (一)Ruby中一切都是对象,包括一个常数.
    比如可以用.class属性来查看一个对象的类型,你可以看下1.class,会发现常数1的类型是Fixnum,1不过是Fixnum的一个实例。还可以使用-37这个Fixnum的实例方法abs来取得绝对值:-37.abs()会返回37
    又如输入一个1.1.class,会返回Float。

    (二)Ruby语法
    Ruby中的类以class开始 以end结束,类名首字母的约定是大写。
    Ruby中的方法以def开始 以end结束,方法名首字母的约定是小写。
    Ruby中的局部变量名首字母的约定是小写。
    Ruby中的构造函数名称为initialize。
    Ruby中的成员变量(实例变量)前导@符,在initialize里进行声明与初始化。
    Ruby中的属性用attr_writer和attr_reader声明,分别对应c#的set,get,使用了attr_accessor是可读也可写
    Ruby中的全局变量前导$符。
    Ruby中的常数(常量)用大写字母开头,约定是全部大写。

    Ruby中任何的表达式都会返回值,sample

    class Rectangle
      
    def initialize(wdth, hgt)
        @width 
    = wdth
        @height 
    = hgt
      end
      
    def width=(wdth)
        @width 
    = wdth
      end
      
    end

    = Rectangle.new(2,3)
    puts r.width 
    = 5 #output 5
    puts r.width # error! because the width not support read

    继续补充下attr_accessor的使用,sample


    class Rectangle
      attr_accessor :width
      attr_accessor :height
      attr_accessor :width2
      attr_accessor :height2
      
      
    def initialize(wdth, hgt)
        @width 
    = wdth
        @height 
    = hgt
      end
      
      
    def area()
        
    return @width * @height
      end
      
      
    def area2()
        
    return @width2 * @height2
      end
      
      
    end

    = Rectangle.new(2,3)
    r.width 
    = 5 # give samename's variable value
    r.height = 5 
    puts r.area() 
    #outputs is 25  

    r.width2 
    = 6 # not samename's variable  create
    r.height2 = 6 
    puts r.area2() 
    # outputs is 36

    上面的代码说明了,在使用attr_accessor的时候,会寻找是否有同名的成员变量,如果有则访问同名成员变量,如果没有会默认创建一个前导@的成员变量

     (三)神奇的操作符重载
    Ruby支持操作符重载,而且很神奇!


    class Rectangle
      attr_accessor :width
      attr_accessor :height
      
      
    def initialize(wdth, hgt)
        @width 
    = wdth
        @height 
    = hgt
      end
      
      
    def area()
        
    return @width * @height
      end
      
      
    def +(addRectangle)
        
    return self.area + addRectangle.area
      end

    end

    r1 
    = Rectangle.new(2,2)
    r2 
    = Rectangle.new(3,3)
    puts r1
    +r2 # operator override
    puts r1+(r2)
    puts r1.
    +(r2) # standard function calling format

    神奇吧,其实把+号理解为一个函数的名字最好不过了,就像最后一个写法,哈哈。

    (四)参数的传递
    参数的传递中有默认值与可变长参数两个比较有特点的地方,其他语言有的,ruby也有。

    1.参数的默认值
    默认值的设置很简单,与其他语言一样,sample

    class Rectangle
      attr_accessor :width
      attr_accessor :height
      
      
    def initialize(wdth = 2, hgt = 2)
        @width 
    = wdth
        @height 
    = hgt
      end
      
      
    def area()
        
    return @width * @height
      end

    end

    r1 
    = Rectangle.new
    puts r1.area

    看到了吧,使用默认值了


    2.可选参数,可变长参数 sample

    class ParamSample
      
    def sayHello(*names)
          puts names.
    class
          puts 
    "Hello #{names.join(",")}!"
      end
      
    end

    ps 
    = ParamSample.new
    ps.sayHello 
    #output Array Hello !
    ps.sayHello("lee","snake"#output Array Hello lee,snake!

    可以看出,可变长参数前缀*号,可变长参数的实质是一个Array,呵呵。

    (一)类变量以及类方法
    sample code

    class BankAccount
      @@interestRate 
    = 6.5
      
    def BankAccount.getInterestRate()
        @@interestRate
      end
      attr_accessor :balance
      
    def initialize(bal)
        @balance 
    = bal
      end
    end

    puts BankAccount.getInterestRate()

    以上代码中描述了如何定义类变量以及如何访问类变量

    Ruby的成员访问修饰关键字分为三种,与c#一样。
    1 private 只能为该对象所调用的方法
    2 protected 只能为该对象及其子对象所调用的方法
    3 public 可以让任何对象所调用的方法

    与c#不同的是,ruby的访问修饰符从定义处开始起作用,直到下一个访问修饰符出现时终止,比如

    class Greeter
      
    def initialize
      end
        
      private
      
    def sayhi()
        puts 
    "hi"
      end
      
      
    def saybye()
        puts 
    "bye"
      end
      
      public
      
    def say()
        sayhi
        saybye
      end
      
    end

    = Greeter.new
    g.say 
    # output hi bye
    g.sayhi # error because the sayhi isn't publics member

    initialize默认就是private的 其他方法默认是public的 成员变量和类变量默认是private的 要用attr_reader或attr_accessor来增加读写控制

     

     

     

    ruby除了支持class外还支持module,module的作用有两个:
    1 当作一组方法和常数的命名空间 防止命名冲突
    2 可以被类mixin(混入),mixin module的类的实例则拥有了模块的方法。


    不同的类混入了同样的模块,则可以拥有同样的功能,而无须去继承某个父类。

    可以通过include一个module来实现c++中的多继承。

    module CircularModule
      PI 
    = 3.1415926
      
    def calculate(diamiter)
        
    return diamiter * PI
      end
    end
      
    class Circular
      include CircularModule
    end
      
    = Circular.new
    puts c.calculate(
    5# output 15.707963
    可以看出来,使用include包含了一个模块后,该类就会包含模块中的方法和常数,方法用 对象名.方法名 ,常数用 类名::常数 。

    md5

    require 'md5'
    puts MD5.hexdigest(
    '')

    sha1

    require 'digest/sha1'
    puts Digest::SHA1.hexdigest(
    ''

    base64

    require 'base64'
    code 
    = Base64.encode64('hallo')
    source 
    = Base64.decode64(code)

    uri

    src = 'abc编码asdf'
    code 
    = URI.encode src
    src 
    = URI.decode code
    puts code
    puts src


    GBK和UTF-8的转换

    用GBK而不要用GB2312,因为GBK不仅包含简体中文,还包括繁体中文等,是一个大字符集。

    # utf8 to gbk
    def u2g(ucode)
      begin
        
    "#{Iconv.conv('gbk','utf-8',ucode)}"
      rescue
         
    " #{ucode} " #如果转换不成功 则不转换 并在字串两边加入空格 避免构造出错误的sql字符串
      end
    end
    这是一个比较不错的从utf-8转换为gbk编码的方法 在网络上抓取的信息 可使用这个方法转换


    RUBY DBI
    ruby和sqlserver交互的时候 使用dbi是一个不错的选择
    dbi有两个比较重要的方法,一个是execute方法,会返回一个结果集,一个是do方法,do方法不会返回结果集,也不会返回受影响的行数,do方法是提交一个事务,而commit方法可以将之前所有使用do方法提交的事务执行,commit会返回受影响的行数。

    需要注意的是,如果使用do方法插入一条数据,而没有commit直接disconnect了,将会导致这条数据插入数据库又被删除,因为你这个时候再插入一条新的数据发现,自增长的主键,被空出一个位置来,比如从3一下跳到了5,所以不要忘记commit。

    Net::HTTP
    Net::HTTP::new方法可以支持4个参数的重载,比如
    req = Net::HTTP.new 'xxxxxx.com',80,'proxy.com',8080
    第三个和第四个参数是指定代理服务器
    第二个参数指定端口 不写的话默认80


    File类的某些方法需要包括'win32/file'
    有些方法不能使用,是因为没有包含win32/file库
    require 'win32/file'
    File.archive? 
    'c:/boot.ini'


    请求URI的时候 使用URI::encode转换一下
    从uri读到的数据写入本地的时候 使用binmode模式
    require 'open-uri'
    uri 
    = 'http://xxx.com/中文.rar'
    data 
    = open(URI::encode(uri)){|f| f.read}
    file 
    = File.new uri[uri.rindex('/'+ 1..uri.length-1], 'w+'
    file.binmode
    file 
    << data
    file.flush
    file.close


    执行sql语句的时候 务必替换特殊字符
    name = "lee's book"
    sql 
    = "update tb_files set [name] = #{name.gsub("'","''")}"

    RUBY脚本后缀名改为.rbw即可在执行时不显示控制台
    arr = "1,2,3".split(',')
    arr.map!{
    |item| item = item.to_i} #一般可以用map!方法来改变原数组内容
    0.upto(arr.length-1){|idx|arr[idx] = arr[idx].to_s} #再将数组内容改回字符串形式 使用upto方法


    fixnum对象的upto和downto方法,可以很方便的作为访问一个数组的索引。

    其实也可以这样做
    (0..arr.length-1).each{|n| arr[n] = arr[n].to_i}


    总之ruby是想怎么写就怎么写 非常方便

    我们经常能看到ruby函数的参数前面有带*号,
     def my_open(*args)
     end
    这是什么意思呢?
    其实也很简单,它的意思是接收任意个参数,并把这些参数组装成一个
    名称为args数组。

     def my_open(*args)
      puts(args.length)
     end
     
     my_open("test.rb","w") 
        
        我们可以看到输出的结果是2,这说明了args是一个带有两个元素的

    发表于

  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    codevs 1501 二叉树最大宽度和高度x
  • 原文地址:https://www.cnblogs.com/lexus/p/1939837.html
Copyright © 2020-2023  润新知