잊지 않겠습니다.

Ruby에서의 standard io method
  1. standard IO method : gets, open, print, printf, putc, puts, readline, readlines, test
  2. IO class 이용 : ruby class 이용

   

IO class
  • Child Class : File, BasicSocket etc...
  • 기본적인 사용방법은 거의 동일하다.
  • 잘짜여진 객체에 대한 논의를 해볼 만 하다.

File IO Class

File Open/Close

file = File.new("testfile", "r")
 # File Process...
file.close

File의 auto close and exception handling

File.Open("testfile", "r") do |file|
 #File Process...
end

File Read/Write

기본적으로 C에서의 기본 IO와 비슷하다. - 이래서 C가 중요한가 보다. -_-

  • file.gets : file에서 one lline을 읽는다.
  • file.get : file에서 one character를 읽는다.

   

읽기를 위한 반복자

IO Stream에서 데이터를 읽기 위해서 사용

  • each_byte : byte 단위로의 return
  • each_line : line 단위로 이용
File.open("testfile") do |file|
 file.each_byte { |ch| putc ch; print "." }
end
File.open("testfile") do |file_data|
 file_data.each_line { |line| print line }
end
C++ iosteam을 이용한 file write
  • <<을 이용한 file write 가능
  • 이는 array, string 등에도 같이 이용 가능하다. [너무나 신기하다. -.-]
write_file = File.open("test_write_file", "w")
write_file << "ykyoon OK"
write_file.close

  

문자열을 이용한 IO
  • 문자열이 파일에 있지 않고, 명령어 인수나 SOAP 서비스를 통한 데이터인 경우에는 문자열 자체를 IO로 사용가능하다.
  • StringIO객체를 이용해서 해결 가능하다.

require 'stringio'

file_data = File.new("vs2005_development.ini")
str_io = StringIO.new("string_io")

file_data.each_line do |line|
    str_io << line
end

print str_io.string

  

Communicate with Network
  • network와의 대화 역시 모두 IO에서 기본적으로 파생되어서 해결 가능하다.
  • Socket Class 들을 이용한 IO를 사용 가능하다.

require 'socket'

client = TCPSocket.open('127.0.0.1', 'finger')
client.send("mysql", 0)

puts client.readlines
client.close

require 'open-uri'

open('http://www.pragmaticprogrammer.com') do |f|
    puts f.read.scan(/<img src="(.*?)"/m).uniq
end

Posted by Y2K
,
  • Module은 Namespaces를 제공해서 이름이 충돌되는 것을 막아준다.
  • 이름은 Mixin 기능을 구현하는 데 사용된다.

모듈의 정의

  • 모듈 상수의 이름은 클래스 상수와 같이 첫문자를 대문자로 한다.
  • 메서드 선언 또한 비슷.

module Moral
    VERY_BAD = 0
    BAD = 1

    def Moral.sin(badness)
        return 'Moral sin : '
    end
end

module Trig
    PI = 3.1415
    def Trig.sin(x)
        return 'sin value '
    end

    def Trig.cos(x)
        return 'cos value '
    end

end

require 'trig'
require 'moral'

y = Trig.sin(Trig::PI / 4)
print y

wrongdoing = Moral.sin(Moral::VERY_BAD)
print wrongdoing

   

MIX-IN

  • Module과 Class는 다르게 움직인다.
  • Module에서는 instance를 가질 수 없게 된다.
  • Module은 Class가 아닌다.
  • Class에서 Module이 포함되게 될 경우에는 Module의 기능을 상속받게 되고, Class의 Instance Method와 동일하게 동작하게 된다.
  • include문을 이용해서 Module을 포함 할 수 있다.

include

  • include문은 ruby에서 선언이 되고, instance를 사용할 때는 아무런 일을 하지 않는다.
  • module의 method를 호출하는 일이 생기게 되면, 그때 추가가 된다.
  • class에 module의 인스턴스 method를 복사하는 것이 아니라, include는 class에 포함될 module에 대한 참조를 얻게 된다.
  • module의 참조를 얻기 때문에, module의 공통 변수나 모듈의 method를 수정하게 될 경우에는 모든 class에서 사용되는 module의 함수가 변경되게 된다.

다른 파일의 참조

requrie

해당 파일을 단 한번만 로드된다.

load

    실행될 때마다 해당 이름 파일을 가진 소스 코드는 포함된다.

Posted by Y2K
,

Error처리는 다른 언어와 기본적으로 비슷하게 throw..catch 방법을 이용한다.
Ruby에서의 예외 계층을 이용해서, 사용하게 된다. (Python에서의 Error 처리 방법과 유사하다.)
begin~rescue~end 구문으로 이용한다.

op_file = File.Open(opfile_name, "w")
begin
    while data = socket.read(512)
        op_file.write(data)
    end
rescue SystemCallError
    $stderr.print "IO failed : " + $!
    op_file.close
    File.delete(op_filename)
    raise
end

 

에러의 발생 방법

1. 단순히 현재의 예외($!)를 다시 발생
raise 
2. RuntimeError 예외를 새로 만들고, 문자열을 넘기는 경우
raise "Error Occur!!" 
3. 예외 Class를 지정해주는 경우
raise InterfaceException, "Keyboard Fail", caller

예외 class를 만들어주고, 그에 대한 메세지를 정한 후에 추적 stack을 정해준다. 일반적으로 Kernel.caller를 통해서 stack의 추적이 이루어진다.

 

Posted by Y2K
,