1

我正在和我一起工作ruby 1.8.6 (2007-03-13 patchlevel 0) [x86_64-linux],我得到了

undefined method `bytes' for #<String:0x2a95ec2268> (NoMethodError)

即使我的代码适用于 ruby​​ 1.8.7。patchlevel 249 我在某处看到您需要require "jcode"为类似的方法添加未定义的错误each_byte。我尝试添加它,但它仍然不起作用。任何建议都非常感谢。

4

2 回答 2

3

在 Ruby 1.8.6 中,您可以使用我的反向移植gem:

require 'backports/1.8.7/string/bytes'

Ta-da,您现在可以访问String#bytes.

您还拥有1.8.7 中引入的所有其他更改。以及 1.9.1 的大部分内容,以及所有即将发布的 1.9.2 等...

于 2010-05-03T13:55:15.260 回答
2

Ruby 1.8.6 没有String#bytes. 这是向后移植到 1.8.7 的 1.9 添加。

您可以像这样自己大致实现它:

class String
  require 'enumerator'

  def bytes(&block)
    return to_enum(:each_byte) unless block_given?
    each_byte &block
  end
end unless ''.respond_to?(:bytes)

[注:我没有检查这是否真的履行了String#bytes100%的合同,但它已经足够接近我的使用了。]

于 2010-05-03T00:39:06.557 回答