学習の準備をしよう †
- Ruby On Rails / Sinatra => フレームワーク
$ ruby -v
- ローカル開発環境に「ruby_lessons」ディレクトリを作成
はじめてのRuby †
print "Hello World"
$ ruby hello.rb
- 1行コメントは「#」
- ブロックコメントは「=begin」「=end」で挟む
オブジェクトを表示するメソッド †
print "Hello World", "world" # 普通に表示
puts "Hello World, again" # 改行付で表示
p "Hello World 3" # オブジェクト型がわかるように表示
変数と定数について †
x = 10
p x
MY_EMAIL = ""
オブジェクトとメソッドを理解しよう †
p "hello".length
クラスとインスタンスを理解しよう †
数値的オブジェクトの演算 †
x = Rational(2, 3)
puts x
x = 5 ** 2 # 25
x = 5 % 2 # 1
x = Rational(2, 3) + Rational(5, 6) # 3/2
RationalメソッドはMacプリインストールRuby環境で使用不可。requireが必要?(MacOS 10.6.8 / ruby 1.8.7)
数値的なオブジェクトで使えるメソッド †
p 10.5.to_i # 10
p 10.5.to_r # 2/3
p 10.8.round # 11
p 10.8.ceil # 11
p 10.8.floor # 10
p rand(100)
p Math.sqrt(2) # 1.4142135623731
文字列オブジェクトを理解する †
x = "hello" # 変数や特殊文字を展開
y = 'hello' # 展開しない
# 特殊文字:\n \t
name = "taguchi"
puts "my name is #{name}"
文字列オブジェクトのメソッド †
p "hello".length # 文字列の長さを表示
p "hello".upcase # 文字列を大文字で表示
p "hello".reverse # 文字列を逆順で表示
p "hello".index("o") # 任意の文字が何文字目にあるか表示
p "hello".include?("o") # 任意の文字が含まれるかどうか表示
- その他のメソッドは公式リファレンスのStringクラスを参照
破壊的メソッドとは? †
s = "hello"
s1 = s.upcase! # 「!」を付与すると「s」も「s1」で上書き
p s
p s1
配列オブジェクトを理解する †
names = ["tabuchi", "fkoji", "dotinstall"]
p names
p names[0] # 0番目の要素
p names[1..2] # 範囲指定:1番目〜2番目
p names[0...2] # 範囲指定:0番目〜2番目、但し2番目は含まない
p names[-1] # 後ろから1番目
配列オブジェクトを操作する †
names[0] = "taguchi_new" # 0番目要素に代入
names[0..1] = ["taguchi_new", "fkoji_new"] # 0〜1番目要素に代入
names[1, 2] = ["a", "b"] # 1番目から2個の要素に代入
names[1, 2] = ["c", "d"] # 1番目から挿入
配列オブジェクトの演算 †
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
p a & b # 積集合を表示
p a | b # 和集合を表示
p a - b # aからbを引いた要素を表示
p a + b # aとbを足した要素を表示(重複あり)
配列オブジェクトのメソッド †
a = [1, 5, 3, 4, 5, 4, 8]
p a.uniq # 重複値を取り除いて表示
p a.sort # 昇順にソートして表示
- 先頭と末尾の操作
- unshift / push:追加
- shift / pop 削除
p a.push(10) # 末尾に10を追加
ハッシュオブジェクトを理解する †
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales["tanaka"]
ハッシュオブジェクトのメソッド †
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales.size # サイズを表示
p sales.empty? # 空であるか?
p sales.key?("tanaka") # キーがあるかどうか?
p sales.has_value?(222) # バリューがあるかどうか?
日付や時間に関するクラスとメソッド †
t = Time.now
p t
p t.year # 年のみ表示
p t.month # 月のみ表示
t = Time.mktime(2011, 2, 24, 9, 0, 0)
p t + 10 # 10秒足して表示
p t.strftime("%Y/%m/%d") # フォーマット指定された表記で表示
$ ruby hello.rb
2011-02-24 09:00:10 +0900
"2011/02/24"
printfメソッドを使おう †
x = "taguchi"
y = 25
printf("%s's score is %d\n", x, y)
# %s:文字列 %d:10進数の数値
$ ruby hello.rb
taguchi's score is 25
printf("%10s's score is %d\n", x, y) # 文字列を10桁で表示(右揃い)
printf("%s's score is %d\n", x, y) # 文字列を10桁で表示(左揃い)
printf("%s's score is %8d\n", x, y) # 数字を8桁で表示
printf("%s's score is %08d\n", x, y) # 数字を8桁で表示(空白を0で埋める)
z = sprintf("%s's score is %d\n", x, y)
p z
if文で条件分岐をしよう †
score = 85
if score >= 80 then # thenは省略可能
puts "great!"
elsif score >= 60
puts "so so..."
else
puts "not so great"
end
if分の別の書き方を理解しよう †
puts "great" if score >= 80
# 条件式?真の時の値:偽の時の値
a = 50
b = 20
max = a > b ? a : b
p max
比較演算子 †
puts "match!" if /taguchi/ =~ "my name is taguchi"
# "my name is taguchi"に"taguchi"が含まれていれば"match!"を表示
case文による条件分岐を理解しよう †
signal = "yellow"
case signal
when "red"
puts "stop!"
when "green", "blue" # 条件を複数指定可能
puts "go!"
when "yellow"
puts "caution!"
else
puts "signal is broken"
end
timesメソッドによる繰り返し処理 †
5.times do
puts "hi!"
end
5.times do |i|
puts "#{i} hi!"
end
$ ruby hello.rb
hi!
hi!
hi!
hi!
hi!
0 hi!
1 hi!
2 hi!
3 hi!
4 hi!
for/eachによる繰り返し処理 †
users = ["taguchi", "fkoji", "dotinstall"]
for user in users do
puts user
end
users = ["taguchi", "fkoji", "dotinstall"]
users.each do |user|
puts user
end
taguchi
fkoji
dotinstall
users = ["taguchi", "fkoji", "dotinstall"]
for i in 1..10 do
puts i
end
1
2
3
4
5
6
7
8
9
10
ハッシュオブジェクトと繰り返し処理 †
- each文を使ったハッシュオブジェクトの繰り返し表示処理
scores = {"taguchi"=>200, "fkoji"=>300, "dotinstall"=>120}
scores.each do |name, score|
printf("%s's score is %d\n", name, score)
end
dotinstall's score is 120
fkoji's score is 300
taguchi's score is 200
while文による繰り返し処理 †
i = 1
while i < 10
puts i
# i = i + 1
i += 1 # 自己代入文
end
1
2
3
4
5
6
7
8
9
メソッドを定義しよう †
# メソッドの定義
def sing
puts "lalala~"
end
# メソッドの呼び出し
sing()
lalala~
def sing(word) # 引数
puts word + word + word + "~"
end
sing("hu")
huhuhu~
def sing(word = "la")
puts word + word + word + "~"
end
sing() # lalala~
sing("hu") # huhuhu~
メソッドの引数、返り値について †
def sing(word, num)
for i in 1..num do
print word
end
puts "~"
end
sing("hu", 10)
huhuhuhuhuhuhuhuhuhu~
def sing(word = "la", num)
s = ""
for i in 1..num do
s += word
end
s += "~"
return s
end
res = sing("hu", 10)
puts res
上記の通りfor文をネストしたメソッドの引数に初期値を設定するとエラー発生(MacOS 10.6.8 / ruby 1.8.7)
クラス作成&インスタンス化 †
# クラス作成
class Monster # 英大文字で開始
def initialize(name) # クラス使用時に必ず呼ばれるメソッド
@name = name # 「@〜」はインスタンス変数(同クラス内はメソッド外で利用可能)
@hp = 100 + rand(100) # インスタンス変数
printf("%s appeared. His hp is %d\n", @name, @hp)
end
def damage
@hp -= 10 + rand(10)
printf("%s's hp is now %d\n", @name, @hp)
printf("%s is now dead!\n", @name) if @hp < 0
end
def heal
@hp += 10 + rand(10)
ptintf("%s's hp is now %d\n", @name, @hp)
end
end
# インスタンス生成
slime = Monster.new("slime") # Monsterクラスのインスタンス「slime」作成
slime.damage
slime.damage
slime appeared. His hp is 166
slime's hp is now 151
slime's hp is now 133