Ruby1.9与Ruby1.8的不兼容处

Ruby1.9与1.8在多个方面存在不兼容性,包括块参数的行为改变、符号和字符串的使用、哈希语法更新、并行赋值的调整、枚举器的改进以及对私有方法的处理。例如,1.9中块参数不再是实例变量,而是局部变量,1.8中的某些语法在1.9中会产生警告或错误。此外,1.9的哈希语法要求使用=>,不再支持旧的语法。
摘要由CSDN通过智能技术生成

  1. formal argument cannot be an instance variable:
    In ruby1.8 it’s possible to use an instance variable as a block argument:
    class Foo
      attr_accessor :bar
      def test
         [1,2,3].each {|@bar| }
         # @bar will be 3 here
      end
    end

    This no longer works in ruby1.9, you as it always creates a new local variable block argument. The equivalent in ruby1.9:

    class Foo
      attr_accessor :bar
      def test
         [1,2,3].each {|bar| @bar=bar }
         # @bar will be 3 here
      end
    end
  2. warning: shadowing outer local variable:
    In ruby1.9 the block arguments are always local to block, in ruby1.8 if there’s an existing variable with the same name, the block parameter will use that one:
    i = 0
    [1,2,3].each {|i| }
    puts i

    This will print 0 in ruby1.9, as the variables named i inside/outside the block are different, and 3 inruby1.8, as here the block reuses the outside variable i.

    As with most warning, this warning doesn’t means that your code is incorrect, only that it might be incorrect.
    For example the code bellow works the same in ruby1.9 and 1.8:

    options = options.inject({}) do |options,pair|
      options[pair.first.to_sym] = pair.last.to_sym; options
    end

    It still makes sense to rewrite the above code just to supress warnings.

    Note: You should set RUBYOPT to -wor start your program with ruby -w, for this warning to show up

  3. syntax error, unexpected ‘,’, expecting tASSOC
    ruby
    1.8 supports , in hash definition, in 1.9 you have to use =>.

    So the following valid ruby1.8:

    {"a","b"}

    has to be rewritten in ruby1.9:

    {"a" => "b"}
  4. invalid multibyte char:
    the default encoding in ruby 1.9 for files is US-ASCII, if you have a non ASCII character in your text file you have to specify the encoding of the source code. You can do it by adding the following line to yourruby file:
    # coding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值