Ruby

ruby の勉強メモ


基本

  • 標準出力方法
puts "Hello World"       # 改行あり
print ("Hello", "World") # 改行なし
  • コマンドラインの引数扱い
puts ARGV[0] + ":" + ARGV[1]
require "optparse"
opts = OptionParser.new
opts.on("-a"){|v| puts "indicated a." } # -a オプションがコマンドラインで指定されていた場合の動作。
opts.parse!(ARGV)
  • if文の書き方
# Pattern 1
if city == "Tokyo" then
  print("東京です")
elsif city == "Osaka" then
  print("大阪です")
elsif city == "Nagoya" then
  print("名古屋です")
else
  print("その他の都市です")
end

# Pattern 2
print("num = ", num) if debug

# Pattern 3 (not if)
unless old < 20 then
 print(Kconv.tosjis("年齢は"), old, Kconv.tosjis("です\n"))
 print(Kconv.tosjis("20歳以上ですのでご利用できます\n"))
end
  • 繰り返し文の書き方
# while statement
num = 0
while num < 4 do
  print("num = ", num)
  num = num + 1
end

# until statement
num = 0
until num >= 4 do
  print("num = ", num)
  num = num - 1
end

# for statement
for num in 0..3 do
 print("num = ", num)
end
  • エラー処理
begin
  puts "Execute"

rescue => ex
  puts ex.class
  puts ex.message
  puts ex.backtarce

ensure
  if ex then
    puts "Error occured"
  else
    puts "No Error"
  end
  • 入力待ち
print "Please any chars : "
line = STDIN.gets
puts "input text: #{line}"
  • OSコマンド呼び出し
# Pattern 1
result = `ls -l`
print result
  # this is simplest.
  # result has result of command.
  # if error occurs, prints error.

# Pattern 2
result = system("ls -lh")
print result
  # 'system' prints result of command(even if error).
  # result has true or false.

# Pattern 3
begin
  result = exec("ls -lh")
  print result
rescue
  puts "error"
end
  # 'exec' prints result of command(even if error).
  # if command is unknown, this can catch exception.

# Pattern 4
result = open("|ls -l")
while !result.eof
  print result.gets
end
  # result has result of command
  # this can write.
  • 環境変数取得
print ENV["LANG"]
  • 設定ファイル読み込み
require 'yaml'
config = YAML.load_file("config.yml")
p config["dictype"][0] #=> "dym"

# in  config.yml
dictype: 
- dym
- rltd

ファイル・ディレクトリ操作

  • 存在確認
print File.exist?("temp.rb")
  • ディレクトリ移動
require  'fileutils'
FileUtils.cd('/usr/local/var/log')
  • ディレクトリ作成
require  'fileutils'
FileUtils.mkdir_p('/usr/local/lib/ruby')
  • ファイル・ディレクトリコピー
require  'fileutils'
FileUtils.cp_r("sample.txt", "tmp")
  • ファイル・ディレクトリ切り取り
require  'fileutils'
FileUtils.mv(['junk.txt', 'dust.txt'], "#{ENV['HOME']}/.trash")
  • ディレクトリ削除
require  'fileutils'
FileUtils.rm('junk.txt')
  • 対象行抽出(grep)
    • OSコマンドを使うのが一番。ちなみに、list からgrepで引っ張る方法はある。
p ['aa', 'bb', 'cc', 'dd', 'ee'].grep(/[bc]/)  # => ["bb", "cc"]
  • 差分
    • OSコマンドを使うのが一番。ちなみに、diffがあるかないかぐらいなら引っ張る方法はある。
require  'fileutils'
FileUtils.cmp('somefile', 'somefile') 
  • sha1sum取得
require 'digest/sha1'
print Digest::SHA1.hexdigest(File.open('temp.rb').read)
  • シムリンク作成
require  'fileutils'
FileUtils.ln_s('/usr/bin/ruby', '/usr/local/bin/ruby')
  # original is /usr/bin/ruby 

その他

  • 日付取得
day = Time.now
print day.strftime("%Y/%m/%d_maint")
  • SVNダウンロード
    • OSコマンドを使うのが一番。 SubversionのRuby用bindingを利用することもできるらしいけど、インストール方法がよくわからん。。
  • CVSダウンロード
    • OSコマンドを使うのが一番。
  • Httpアクセス
require 'net/http'
Net::HTTP.version_1_2   # おまじない
Net::HTTP.start('www.iana.org', 80) {|http|
  response = http.get('/index.html')
  puts response.body
}

# use Proxy
require 'net/http'
Net::HTTP.version_1_2   # おまじない
Net::HTTP::Proxy("your.proxy.addr", 8080).start('www.iana.org', 80) {|http|
  response = http.get('/index.html')
  puts response.body
}

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2011年03月20日 22:57