Skip to content

Instantly share code, notes, and snippets.

@tyabuta
Created November 23, 2012 04:29
Show Gist options
  • Save tyabuta/4134008 to your computer and use it in GitHub Desktop.
Save tyabuta/4134008 to your computer and use it in GitHub Desktop.
Ruby CodeSnippet
######################################################################
# Ruby CodeSnippet
######################################################################
# --------------------------------------------------------------------
# Rubyでの起動を指定。一行目に記述する必要あり。
# -KuオプションでUTF-8を指定。日本語を出力する時にないと文字化けする。
# --------------------------------------------------------------------
#!/usr/bin/ruby -Ku
# --------------------------------------------------------------------
# オプション解析
# OptionParser#versionは
# -vまたは --versionオプションが指定された時に表示されるバージョン情報
# --------------------------------------------------------------------
require 'optparse'
OPTS = {}
opt = OptionParser.new
opt.version = "1.0.0 (c) tyabuta 2012."
# -f, --flagオプションが指定されている場合、OPTS[:flag]がtrue
opt.on("--flag", "Description of --flag") { |v| OPTS[:flag] = v }
# --mesage="hoge" としてオプション引数を指定できる。
# オプション引数がないと、OptionParser::MissingArgumentの例外が発生する。
opt.on("--message=Message", "Description of --message") { |v| OPTS[:message] = v }
begin
opt.parse(ARGV)
rescue OptionParser::InvalidOption => e
puts "無効なオプションが渡されました。#{e}"
rescue OptionParser::MissingArgument => e
puts "オプション引数が指定されていません。#{e}"
end
# --------------------------------------------------------------------
# /tmpディレクトリ内に一時ディレクトリを作成する。
# ブロックから抜けると一時ディレクトリは削除される。
# --------------------------------------------------------------------
require 'tmpdir'
Dir.mktmpdir(){ |dir|
puts dir # => /tmp/xxxx
}
# --------------------------------------------------------------------
# テキストファイルを一行ずつ読み込み
# open関数でブロック記法にすると、ファイルは自動でcloseされる。
# line: 一行毎の文字列
# index: ゼロベースのインデックス
# --------------------------------------------------------------------
begin
open(path, "r") { |hfile|
hfile.each_line.with_index { |line, index|
# 末尾の改行文字を削除
line.chomp!
puts "#{index + 1}: #{line}"
}
} # file close
rescue
# 例外処理
puts "file open error."
end
# --------------------------------------------------------------------
# HTTPリクエストを送り、結果を取得する。
# --------------------------------------------------------------------
require 'net/http'
url = "http://tyabsite.net/"
uri = URI.parse(url)
result = Net::HTTP.new(uri.host, uri.port).start { |http|
http.request(Net::HTTP::Get.new(uri.path))
}
p result
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment