ruby1.8 1.9问题

    技术2025-09-19  144

    1:正式的参数不能使实例变量

      Ruby1.8

       class Foo attr_accessor :bar def test [1,2,3].each {|@bar| } # @bar will be 3 here end end

      Ruby1.9

      class Foo attr_accessor :bar def test [1,2,3].each {|bar| @bar=bar } # @bar will be 3 here end end

    2:覆盖外部局部变量

      i =0 [1,2,3].each { |i| } puts i ruby1.8输出3 ruby1.9输出0

    3: hash语法 ” , “ 问题

      ruby 1.8    {"a","b"}    => {"a"=> "b"}

      ruby 1.9     {"a" =>"b"}

    4:字符

       默认是  US-ASCIi  码   如果不是的话 用 coding :utf-8

    5: String的 ‘to_a’方法未定义

      1.8    :  string.to_a

      1.9    :  string.lines.to_a

    为了解决兼容性问题keyi :

        if str.respond_to?(:lines) then lines = string.lines.to_a else lines = string.to_a end

    6: 关键字 then , ; /n  case if 可以使用: 代替

          1.8:

             case 'test' when'test':print 'OK' end

       1.9:

         case 'test' when'test' then print 'OK' end

     

    7:no such file to load -base64:

     

      require "base64": ruby 1.9 ships without base64. You should use Array#pack, unpack require 'base64' enc = Base64.encode64('Send reinforcements') plain = Base64.decode64(enc) In ruby1.9 you can write: enc = ['Send reinforcements'].pack( 'm' ) plain = enc.unpack( 'm' )[0]  

    8:'结构体 RStirng没有成员‘ptr’ len

       In ruby1.9 for the RString in C extensions was changed because of optimization, you should use the RSTRING_LEN, RSTRING_PTR macros instead of directly accessing the len, ptr members. len = RSTRING(foo)->len ptr = RSTRING(foo)->ptr Should be changed to len = RSTRING_LEN(foo); ptr = RSTRING_PTR(foo);

    9:成员改变从Strings转化到Symbols

      Object.methods.include?("to_s") The ruby1.9 version is: Object.methods.include?(:to_s) And the following works in ruby1.8 and 1.9: object.respond_to?(:some_method)

    10:TypeErro:不能分配nil;要用Hash#delete 代替

     

    n ruby1.8 you can remove an environment variable by setting it to nil. In ruby1.9 use the delete method instead: ENV.delete('MY_ENV_VARIABLE')

     

     

     

     

     

     

     

     

     

     

     

     

     

    最新回复(0)