- テキストファイルの各行から,正規表現にマッチした行を取り除いて表示する
- 正規表現::Ruby
- 配列あれこれ
- 簡易版wcコマンド(例外処理rescure)
- ディレクトリとファイルの一覧を配列で取得
- モジュールを作る
- テキストデータを1行ずつ読み込んで表示する
- テキストデータの行頭と行末に文字列を追加する
テキストファイルの各行から,正規表現にマッチした行を取り除いて表示する
マッチした部分だけを取り除くのではなく,行ごと取り除く
filename = ARGV[0]
file = open(filename)
while text = file.gets
if (text =~ /\#\+BEGIN/) || (text =~ /\#\+END/)
next
else
print text
end
end
配列あれこれ
a[n]からa[m]まで
a[n..m]
a[n]からa[m-1]まで
a[n...m]
a[n]からlen個取り出す
a[n, len]
要素を挿入
インデクスnから任意の個数挿入: a[n, 0]
a = [0,1,2,3,4,5] => [0, 1, 2, 3, 4, 5]
a[2, 0] = ["a", "b"] => ["a", "b"]
a => [0, 1, "a", "b", 2, 3, 4, 5]
置き換えもできる。
簡易版wcコマンド(例外処理rescure)
## 簡易版wcコマンド
ltotal = 0 # 行数の合計
wtotal = 0 # 単語数の合計
ctotal = 0 # 文字数の合計
ARGV.each do |file|
begin
input = open(file)
l, w, c = 0, 0, 0
while line = input.gets
l += 1
c += line.size
line.sub!(/^\s+/, "") # 行頭の空白を削除
ary = line.split(/\s+/) # 空白文字で分解する
w += ary.size
end
input.close
printf("%8d %8d %8d %s\n", l, w, c, file) # 出力の整形
ltotal += l
wtotal += w
ctotal += c
rescue => ex
print ex.message, "\n" # 例外のメッセージを出力
end
end
printf("%8d %8d %8d %s\n", ltotal, wtotal, ctotal, "total")
ディレクトリとファイルの一覧を配列で取得
シェルのワイルドカード風のパターンマッチ
Dir.glob("*.html")
| パターン |
意味 |
| * |
任意の文字列 |
| ** |
「*/」の任意の回数の繰り返し |
| ? |
任意の一文字 |
| [abc] |
a, b, cのいずれか一文字 |
| [^abc] |
a, b, c以外の一文字 |
| [a-z] |
ASCII文字のaからzのいずれか |
| {foo,bar,baz} |
foo,bar,bazのいずれか |
Dir.glob("*.[ch]").sort
モジュールを作る
module モジュール名
モジュールの定義
end
例
module HelloModule
Version = "1.0" # 定数の定義
def hello(name) # メソッドの定義
print "Hello, ", name, ".\n"
end
module_function :hello # helloをモジュール関数として公開する
end
## includeしない
p HelloModule::Version # 定数の呼び出し
HelloModule.hello("Alice") # メソッドの呼び出し
## includeする
include HelloModule
p Version
hello("Alice")
テキストデータを1行ずつ読み込んで表示する
filename = ARGV[0]
file = open(filename)
while text = file.gets
print text
end
file.close
file.each_line do |line|
print line
end
とかでもいける
テキストデータの行頭と行末に文字列を追加する
テキストデータを読み込み行末に文字を追加するには,改行文字を取り除かないといけない
file = open(ARGV[0], "r")
while text = file.gets
text = text.chomp # 改行文字を取り除く
print "(",text,")\n"
end
file.close
以下未整理
繰り返し
for文
一般的な構文
for 変数 in オブジェクト do
処理
end
doは省略可能.
#例
sum = 0
for i in 1..5
sum = sum + i
end
print sum,"\n"
「..」や「...」は範囲オブジェクトである.
オブジェクトを配列にした場合の例を載せる.
names = ["aa" , "bb" , "cc" , "dd"]
for name in names
print name,"\n"
end
配列の中から1つずつ要素を取り出して、それぞれを表示する.
while文
while 条件 do
処理
end
### 例 : 1から10までの数を順番に表示する
i = 1
while i <= 10
print i, "\n"
i = i + 1
end
timesメソッド
回数が決まっているときはこっちが楽.
繰り返す回数.times do
処理
end
条件分岐
if文
if 条件 then
文
end
if 条件1 then
文1
elsif 条件2 then
文2
else
文3
end
ファイル入出力
IOクラスのサブクラスであるFileクラスで行える.
Fileクラスにはファイルの削除やファイルの属性変更など,ファイルシステムに特化した機能が実装されているが,
基本的な入出力操作はIOクラスから受け継いだメソッドを使う。
ファイルを開いて新しいFileオブジェクトを得るには,
openメソッド,またはFile.openメソッドを使う。
io = open(file , mode)
io = File.opne(file , mode)
modeには以下のモードを指定する.
| モード |
意味 |
| "r" |
読み込み専用でファイルを開く |
| "r+" |
読み込み / 書き込み用としてファイルを開く |
| "w" |
書き込み専用でファイルを開く.ファイルがなければ新たに作成する.またすでに存在する場合には,ファイルサイズを0にする. |
| "w" |
読み込み / 書き込み用,その他は"w"と同じ |
| "a" |
追加書き込み専用でファイルを開く,ファイルがなければ新たに作成する |
| "a+" |
読み込み / 追加書き込み用としてファイルを開く.ファイルがなければ新たに作成する. |
算術演算
| 演算子 |
演算 |
| + |
加算 |
| - |
減算 |
| * |
乗算 |
| / |
除算 |
| % |
剰余 |
| ** |
べき乗 |
IntegerオブジェクトとFloatオブジェクトを計算した結果はFloatオブジェクトになる.
割り算
数値オブジェクトには,/と%の他にも割り算に関するメソッドがある.
x.divmod(y)
xをyで割ったときの商と余りを,配列にして返す.
Mathモジュール
三角関数や対数関数などの数学っぽいやつの演算で使うモジュール.
Math.sqrt(2)
のようにモジュール名を明示的に指定する方法と,
include Math
でインクルードする方法がある.
#例
f = 2
p Math.sqrt(f)
include Math # Mathモジュールのインクルード
p sqrt(f)
Mathモジュールで提供されるメソッドで,よく使いそうなメソッド
| メソッド名 |
意味 |
| cos(x) |
余弦関数 |
| sin(x) |
正弦関数 |
| exp(x) |
指数関数 |
| log(x) |
底をeとする対数 |
| log10(x) |
底を10とする対数 |
| lox2(x) |
底を2とする対数 |
| sqrt(x) |
平方根 |
Mathモジュールが提供する定数
複素数
require "complex" # Ruby 1.9では不要
a = Complex(3, 5)
b = Complex(2, 4)
p a*b # => Complex(-14, 22)
実部と虚部を取り出すには,Complex#real,Complex#image
p a.real
p a.image
配列
配列の作り方
nums = [1, 2, 3, 4, 5]
strs = ["a", "b", "c", "d"]
他には,Arraw.newを使う.
a = Array.new
p a #=> []
a = Array.new(5)
p a #=> [nil, nil, nil, nil, nil]
a = Array.new(5, 0)
p a #=> [0, 0, 0, 0, 0]
要素が文字列で空白を含まないなら,%wを使える.
lang = %w(Ruby Perl Python [[Scheme]] Pike REBOL)
p lang #=> ["Ruby", "Perl", "Python", "Scheme", "Pike", "REBOL"]
インデックスの使い方
配列にインデックスを指定することで,要素を取り出せる.
a[n]
18.
18.9 多重代入
メソッドから複数の返り値を得る。
def hogehoge()
...
return x, y, z
end
このメソッドを使う際に,
a, b, c = hogehoge()
とすると,
a => x, b => y, c => zとなる。
最終更新:2011年12月22日 23:17