オブジェクト指向のスクリプト言語である。
Perlのように簡単にプログラムできて、Perlより読みやすく、完全なオブジェクト指向の言語と言われている。
文法はC(C++)、シェル、sed、Awk、Perl、Pythonなどを合わせて独自にしたような感じである。
Rubyはオブジェクト指向のスクリプトなので、クラスを作成しないと本格的なプログラミングはできないが、ここでは簡単な例で雰囲気だけをつかんで欲しい。
コマンドライでの実行方法。
#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が新しいウインドウの中に表示される #
データファイル中の数値の合計を出力するスクリプト。
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 #
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のデータが出力される #