Ruby 入門 -2ページ目

Ruby 入門

~ Ruby初心者による逆引き備忘録 ~

<< 目次

module を使ってみる。

module TestModule
def adder a, b
return a + b
end
module_function :adder
end

# test

p TestModule.adder(1,2)

または、

include TestModule
p adder(1,2)

実行結果

3

module の呼び出し方は、上記のように module.method と include してから method と2種類ある。
ちなみに、module.method で呼び出す場合は、module_function :adder が必須となる。
しないと以下のようなエラーが出て実行できないので注意。

undefined method `adder' for TestModule:Module (NoMethodError)

<< 目次
<< 目次

配列の中に配列を定義する。

array = [ [1,2,3],
[4,5,6],
[7,8,9] ]

array.each{|a|
p a
}

これは、以下と同じ。

array[0] = [1,2,3]
array[1] = [4,5,6]
array[2] = [7,8,9]

array.each{|a|
p a
}

実行結果

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

<< 目次
<< 目次

正規表現自体を変数としてメッソドの引数として扱う。
keyword の中身を動的に変化させればいろいろ使えそう。

def search str, keyword
if /#{keyword}/ =~ str
return "\"#{str}\" => much!"
else
return "\"#{str}\" => not much!"
end
end

# test

str = "This is search test"

puts search(str, "a")
puts search(str, "z")
puts search(str, "is")

実行結果

"This is search test" => much!
"This is search test" => not much!
"This is search test" => much!

<< 目次
<< 目次

ハッシュを重ねることを、多重連想配列、多重ハッシュ、とかいったりする。
実際に書いてみるとわかりやすい、なるほど。

h = Hash.new

h['1'] = Hash.new
h['2'] = Hash.new

h['1']['a'] = "1a"
h['2']['b'] = "2b"
h['2']['c'] = "2c"

puts h['1']['a']
puts h['2']['b']
puts h['2']['c']

実行結果

1a
2b
2c

<< 目次

<< 目次

日付日時でログ表示する為のメソッド。

require 'date'

def logging_message string
return DateTime.now.strftime("%Y-%m-%d %H:%M:%S #{string}\n")
end

# test

puts logging_message("error.")
sleep 1

puts logging_message("warning.")
sleep 1

実行結果

2010-05-04 00:14:48 error.
2010-05-04 00:14:49 warning.

<< 目次
<< 目次

以下を test.cgi という名前で作成し、cgi-bin 相当の dir において
http://localhost/cgi-bin/test.cgi とかにアクセスすれば、現在時刻が見えるはず。

require 'date'

print "Content-type: text/html; \n\n"
now = DateTime.now.strftime('%Y-%m-%d %H:%M:%S')
print now

さらに値をブラウザ経由で渡して処理をさせて表示したいという時は、
require cgi をして form で値を渡し、cgi[xxx] で取り出せばよい。

<< 目次
<< 目次

そーいえば、ruby で for文てあまり使ったことないなーと思いながら書いてみた。

for i in [ 1, 2, 3, 4, 5 ]
puts i
end

これは、こんな風に書く事も可能

for i in 1..5
puts i
end

実行結果

1
2
3
4
5

<< 目次
<< 目次

Ruby の変数

インスタンス変数

@var


クラス変数

@@var


グローバル変数

$var


疑似変数

true false nil


<< 目次
<< 目次

each という便利なイテレータメソッドがあるので使ってみる。

array = [ "a", "b", "c", "d", "e" ]

array.each{|x|
puts x
}

実行結果

a
b
c
d
e


<< 目次