2011-11-26 3 views
3

Ruby 1.9에서 파일 및 IO 라이브러리가 변경되었습니다. 이제는 데이터를 항상 인코딩 된 문자열 (예 : UTF-8)로 해석하고 리턴 된 값은 항상 문자열 인 것처럼 보입니다.Ruby 1.9의 파일에서 바이트를 읽으려면 어떻게해야합니까?

데이터 수정이나 해석없이 Ruby 1.9 바이트 단위로 파일을 읽어야합니다. 인코딩 된 문자열이 아닌 바이트 시퀀스를 읽고 싶습니다.

어떻게하면 좋을까요?

답변

3

나는 내가 쓴 보석에서 비슷한 문제가 있었다. 여기에 관련 코드는 다음과 같습니다 는 (그것을 설정하는 것입니다 호출)

# ============================================================================== 
# Loading Libraries and Stuff needed for Ruby 1.9 vs 1.8 Compatibility 
# ============================================================================== 
# the idea here is to define a couple of go-between methods for different classes 
# which are differently defined depending on which Ruby version it is -- thereby 
# abstracting from the particular Ruby version's API of those classes 

if RUBY_VERSION >= "1.9.0" 
    require "digest/md5" 
    require "digest/sha1" 
    include Digest 

    require 'fileutils'  # replaces ftools 
    include FileUtils::Verbose 

    class File 
    def read_bytes(n) # returns a string containing bytes 
      self.bytes.take(n) 
    end 
    def write_bytes(bytes) 
     self.syswrite(bytes) 
    end 
    def get_byte 
     self.getbyte  # returns a number 0..255 
    end 
    end 

    ZEROBYTE = "\x00".force_encoding(Encoding::BINARY) unless defined? ZEROBYTE 

else # older Ruby versions: 
    require 'rubygems' 

    require "md5" 
    require "sha1" 

    require 'ftools' 
    def move(a,b) 
    File.move(a,b) 
    end 

    class String 
    def getbyte(x) # when accessing a string and selecting x-th byte to do calculations , as defined in Ruby 1.9 
     self[x] # returns an integer 
    end 
    end 

    class File 
    def read_bytes(n) 
     self.read(n) # should use sysread here as well? 
    end 
    def write_bytes(bytes) 
     self.write(bytes) # should use syswrite here as well? 
    end 
    def get_byte  # in older Ruby versions <1.9 getc returned a byte, e.g. a number 0..255 
     self.getc # returns a number 0..255 
    end 
    end 

    ZEROBYTE = "\0" unless defined? ZEROBYTE 
end 
+0

Ruby 2.0.0 이상부터 'IO # each_byte'가'IO # bytes'보다 선호됩니다. –

+1

지적 해 주셔서 고맙습니다! – Tilo

1

IO가 bin 파일 모드로 방법이있다 (당신은이 문을 필요로 필요하지 않습니다) 개행 문자 인코딩 변환을 비활성화한다. File 클래스는이 메서드를 상속합니다.

관련 문제