Ruby覚え書き
#introRuby
#コメント
#実行
ruby -e 'puts ("hello, world")'
#変数の文字列内展開
var = "world"
puts "hello #{var}"
> hello world
#条件分岐
i = 1
if i < 0
puts "負"
elsif i > 0
puts "正"
else
puts "零"
end
> 正
if i % 2 == 1 : puts "奇数です。" end #if文を後置すること、thenの代わりに:を利用することも可能
> "奇数です"
#制御構文
i = 0
while i < 10 #i < 10が成り立つ間だけ繰り返し
puts i
i += 1
end
until i < 1 #i < 1になるまで繰り返し
puts i
i -= 1
end
sum = 0
i = 0
for i in (1..10) #1〜10まで繰り返し
sum += i
end
10.times do |i| #10回繰り返し
puts i
end
10.times { |i| puts i} #10回繰り返し。do~endの代わりに{}も利用可
array = ["A", "B", "C"] #配列の全要素分繰り返し
array.each { |string| puts string}
i = 0
loop {puts i+=1} #無限ループ
#関数定義
def hello(name)
puts "Hello, #{name}"
end
hello("World.")
>Hello, World.
#クラス定義
class Myclass
def initialize(name) #コンストラクタ
@name = name
end
def hello
puts "Hello, #{@name}"
end
end
a = Myclass.new("World")
a.hello
#継承
# スーパークラスの定義
class MyClass
def hello
puts "Hello!"
end
def bye
puts "Bye!"
end
end
# サブクラスの定義
class MySub < MyClass
def hey
puts "hey!"
end
def hello
puts "hello!!!!!!!!!!!!!!"
end
end
classSuper = MyClass.new
classSuper.hello
classSuper.bye
classSuper.hey #サブクラスのメソッドは利用できない
classSub = MySub.new
classSub.hey
classSub.hello
classSub.bye #スーパークラスのメソッドを利用できる
#例外処理
begin
f = File.open("c:/test.txt")
print f.read
f.close
rescue => ex
p ex
retry
ensure #例外の発生にかかわらず必ず実行される処理
puts "end"
end
#配列
ary = [1, 2, 3] #配列の標準的な定義方法
ary = %w(A B C D E) #文字列を%wで指定することにより、空白区切りで文字列配列化する
ary[1..3]
ary[-3..-1]
ary << "F" # add list
ary[3,2] = ["G", "H"]
ary = [1, 2, 3, 4, 5]
ary.map { |i| i / 5 } #列の各要素に対してブロックを実行し、結果を配列で返す
#ハッシュ
hash = {"名詞" => 1, "助詞" => 0, "形容詞" => 3 }
hash.each { |key, value| puts "#{key}, #{value}"
hash.has_key?("代名詞") #=> false
hash.has_value?("3") #=> true
hash.store("代名詞", 2)
#破壊的:オブジェクトの中身を変更するメソッド。メソッド名に!を付けて呼ぶ
ary = [1, 2, 3]
ary.map {|i| i**i} #aryの中身は変更無し
ary.map! {|i| i**i} #aryの中身に変更有り
#ファイル処理
#ファイル一気に読む
fileName = "c:/test.txt"
f = open(fileName)
print f.read
f.close
#ファイル一行ずつ読む
File::open(fileName) {|f| f.each {|line| print line}}
#ファイル指定行を読む
open(fileName) {|file| print file.readlines[10]}
#ファイルに書き込む
f = File.open(fileName, 'w')
f.puts "hello world"
f.close
#DB(SQLite)
require 'sqlite3'
db = SQLite3::Database.new("test.db")
sql = "select id, name from test"
db.execute(sql) { |id, name| print "#{id}, #{name}"}
#ディレクトリ操作
puts "Current Directory :"
Dir.pwd #カレントディレクトリ取得
puts "Change Directory to /tmp."
Dir.chdir("/tmp") #ディレクトリ移動
dir = Dir.open(".") #ディレクトリ内のファイル/フォルダを取得
dir.each { |filename| filename}
Dir.glob("*.htm\0*.html") #ディレクトリ内のファイルをパターンマッチで取得。複数パターンを使う場合は\0で区切る
Dir.glob("pub/**/*.txt") #ディレクトリ内を再起検索
Dir.mkdir("test") #ディレクトリ作成
Dir.rmdir("test") #ディレクトリ削除※ディレクトリが空のときのみ
File.rename("fileName", "NewFileName") #ファイル名変更。違うフォルダを指定した場合はファイルのコピー・移動になる
File.delete("fileName") #ファイル削除
File.basename(fileName) #ファイル名のみ取得
File.dirname(fileName) #ディレクトリ名のみ取得
File.stat(filename).mtime #ファイルの最終更新日取得
File.stat(filename).size #ファイルサイズ取得
#時間
Time.new.hour.to_s + ":" + Time.new.min.to_s
t = Time.new
p t.strftime("%Y年%m月%d日%H時%M分%S秒")
p t.strftime("%d, %B (%A)")
t1 = Time.now
sleep(5)
t2 = Time.now
puts "#{t2 - t1}秒経過しました。"
シンボル、重要である
参考
逆引きRuby http://www.namaraii.com/rubytips/
Rubyプログラミング入門 http://www.ipa.go.jp/software/open/ossc/download/subject1-2_lesson.pdf