Ruby

Rubyとは

オブジェクト指向のスクリプト言語である。
Perlのように簡単にプログラムできて、Perlより読みやすく、完全なオブジェクト指向の言語と言われている。
文法はC(C++)、シェル、sed、Awk、Perl、Pythonなどを合わせて独自にしたような感じである。

Ruby の使用例

Rubyはオブジェクト指向のスクリプトなので、クラスを作成しないと本格的なプログラミングはできないが、ここでは簡単な例で雰囲気だけをつかんで欲しい。

Ruby の簡単な使い方 その1

コマンドライでの実行方法。

#ruby -e 'print "Hello World\n"'    <- おなじみHello World
Hello World
#

同じHello Worldのウインドウ版。
以下のプログラムをhello.rbという名前で作る。

require "tk"
TkLabel.new {
	text 'Hello World'
	pack
}
Tk.mainloop

# ruby hello.rb     <- Hello Worldが新しいウインドウの中に表示される
#

Ruby の簡単な使い方 その2

データファイル中の数値の合計を出力するスクリプト。

total = 0
while $_ = gets()
	datas = $_.split(/ /)
	while i = datas.shift()
		total += i.to_i()
	end
end
print total, "\n"

#  cat data    <- サンプルデータ
1 2 3
4 5 6
7 8 9
#  ruby total.rb < data    <- 実行
45
#

Ruby の簡単な使い方 その3

http://www2.gol.com/users/abetmhr/index.htmlを取得するスクリプト。

require "socket"

host = "www2.gol.com"
port = 80
sock = TCPsocket.open(host, port)
com = "GET /users/abetmhr/index.html HTTP/1.0" + "\r\n\r\n"
sock.write(com)
print sock.read

#  ruby gethtml.rb    <- 実行
ここにhttp://www2.gol.com/users/abetmhr/index.htmlのデータが出力される
#

参考


Prev
Home | Contents
abe@injapan.net