Rubyの基礎
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
]
開始行:
** 学習の準備をしよう [#j3b16628]
- 洗練されたオブジェクト指向型言語
- Ruby On Rails / Sinatra => フレームワーク
- 公式サイト
-- Ruby(日本語): http://www.ruby-lang.org/ja/
-- Ruby(英語): http://www.ruby-lang.org/en/
-- Ruby On Rails: http://rubyonrails.org/
-- Sinatra: http://www.sinatrarb.com/
- 環境(MacOS Xには標準でプリインストール)
-- Rubyのバージョンを確認
$ ruby -v
- ローカル開発環境に「ruby_lessons」ディレクトリを作成
** はじめてのRuby [#k7d4c298]
- 「hello.rb」を作成
print "Hello World"
- 実行方法
$ ruby hello.rb
- 文の終りは「改行」か「;」
- 1行コメントは「#」
- ブロックコメントは「=begin」「=end」で挟む
** オブジェクトを表示するメソッド [#b9e2aac5]
print "Hello World", "world" # 普通に表示
puts "Hello World, again" # 改行付で表示
p "Hello World 3" # オブジェクト型がわかるように表示
** 変数と定数について [#v14cccae]
- 変数:オブジェクトにつける名札
-- 英子文字か_で始まる
-- 予約語はなし(例:end)
x = 10
p x
- 定数:全部大文字、変更禁止
MY_EMAIL = ""
** オブジェクトとメソッドを理解しよう [#l718f0cb]
- オブジェクト指向型言語で使われる用語
-- オブジェクト:便利な命令が詰まったデータ型
-- メソッド:便利な命令
p "hello".length
** クラスとインスタンスを理解しよう [#hb365e5e]
- クラス:設計図
- インスタンス:実体化されたデータ
- [[公式リファレンス:http://www.ruby-lang.org/en/]]より標...
** 数値的オブジェクトの演算 [#g57e9f58]
- 分数
x = Rational(2, 3)
puts x
- 演算子:+ - * / % **
x = 5 ** 2 # 25
x = 5 % 2 # 1
x = Rational(2, 3) + Rational(5, 6) # 3/2
- %%&color(red){RationalメソッドはMacプリインストールRuby...
- &color(red){ruby 1.9.2では改善};
** 数値的なオブジェクトで使えるメソッド [#c9b4c266]
- 型変換
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
** 文字列オブジェクトを理解する [#ree415fa]
x = "hello" # 変数や特殊文字を展開
y = 'hello' # 展開しない
# 特殊文字:\n \t
- 変数の展開
name = "taguchi"
puts "my name is #{name}"
** 文字列オブジェクトのメソッド [#nc393247]
p "hello".length # 文字列の長さを表示
p "hello".upcase # 文字列を大文字で表示
p "hello".reverse # 文字列を逆順で表示
p "hello".index("o") # 任意の文字が何文字目にあるか表示
p "hello".include?("o") # 任意の文字が含まれるかどうか表示
- その他のメソッドは公式リファレンスのStringクラスを参照
** 破壊的メソッドとは? [#f5574e8b]
s = "hello"
s1 = s.upcase! # 「!」を付与すると「s」も「s1」で上書き
p s
p s1
** 配列オブジェクトを理解する [#hb78b93a]
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番目
** 配列オブジェクトを操作する [#sba5ca95]
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番目から挿入
** 配列オブジェクトの演算 [#ua423d56]
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を足した要素を表示(重複あり)
** 配列オブジェクトのメソッド [#e07d9c89]
a = [1, 5, 3, 4, 5, 4, 8]
p a.uniq # 重複値を取り除いて表示
p a.sort # 昇順にソートして表示
- 先頭と末尾の操作
-- unshift / push:追加
-- shift / pop 削除
p a.push(10) # 末尾に10を追加
** ハッシュオブジェクトを理解する [#n94fc922]
- ハッシュオブジェクト(連想配列)
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales["tanaka"]
** ハッシュオブジェクトのメソッド [#j7a074a5]
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales.size # サイズを表示
p sales.empty? # 空であるか?
p sales.key?("tanaka") # キーがあるかどうか?
p sales.has_value?(222) # バリューがあるかどうか?
** 日付や時間に関するクラスとメソッド [#ya8bdb5b]
- 現在時刻
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メソッドを使おう [#a8760cd5]
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桁で表示(...
- 文字列を返す「sprintf」
z = sprintf("%s's score is %d\n", x, y)
p z
** if文で条件分岐をしよう [#l8a35645]
score = 85
if score >= 80 then # thenは省略可能
puts "great!"
elsif score >= 60
puts "so so..."
else
puts "not so great"
end
** if分の別の書き方を理解しよう [#l7293639]
- 簡略的な書き方
puts "great" if score >= 80
- 条件演算子 if ... else ...
# 条件式?真の時の値:偽の時の値
a = 50
b = 20
max = a > b ? a : b
p max
** 比較演算子 [#kd36a62b]
- 不等号/不等号:< > >= <= == !=
- 正規表現の文字列マッチング: =~
puts "match!" if /taguchi/ =~ "my name is taguchi"
# "my name is taguchi"に"taguchi"が含まれていれば"match!...
- 論理演算子: && ||
** case文による条件分岐を理解しよう [#k19540d7]
signal = "yellow"
case signal
when "red"
puts "stop!"
when "green", "blue" # 条件を複数指定可能
puts "go!"
when "yellow"
puts "caution!"
else
puts "signal is broken"
end
** timesメソッドによる繰り返し処理 [#s0876ec2]
- 繰り返し処理
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による繰り返し処理 [#tfde8670]
- for文
users = ["taguchi", "fkoji", "dotinstall"]
for user in users do
puts user
end
- each文
users = ["taguchi", "fkoji", "dotinstall"]
users.each do |user|
puts user
end
- 実行結果
taguchi
fkoji
dotinstall
- for文(単純繰り返し)
users = ["taguchi", "fkoji", "dotinstall"]
for i in 1..10 do
puts i
end
- 実行結果
1
2
3
4
5
6
7
8
9
10
** ハッシュオブジェクトと繰り返し処理 [#ed6d8f32]
- each文を使ったハッシュオブジェクトの繰り返し表示処理
scores = {"taguchi"=>200, "fkoji"=>300, "dotinstall"=>1...
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文による繰り返し処理 [#cac0b679]
- while文(自己代入)
i = 1
while i < 10
puts i
# i = i + 1
i += 1 # 自己代入文
end
- 実行結果
1
2
3
4
5
6
7
8
9
** メソッドを定義しよう [#d5907f12]
# メソッドの定義
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~
** メソッドの引数、返り値について [#ie05008c]
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
- %%&color(red){上記の通りfor文をネストしたメソッドの引数...
- &color(red){ruby 1.9.2では改善};
** クラス作成&インスタンス化 [#gcceccda]
# クラス作成
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.damage
slime.damage
- 実行結果
slime appeared. His hp is 166
slime's hp is now 151
slime's hp is now 133
終了行:
** 学習の準備をしよう [#j3b16628]
- 洗練されたオブジェクト指向型言語
- Ruby On Rails / Sinatra => フレームワーク
- 公式サイト
-- Ruby(日本語): http://www.ruby-lang.org/ja/
-- Ruby(英語): http://www.ruby-lang.org/en/
-- Ruby On Rails: http://rubyonrails.org/
-- Sinatra: http://www.sinatrarb.com/
- 環境(MacOS Xには標準でプリインストール)
-- Rubyのバージョンを確認
$ ruby -v
- ローカル開発環境に「ruby_lessons」ディレクトリを作成
** はじめてのRuby [#k7d4c298]
- 「hello.rb」を作成
print "Hello World"
- 実行方法
$ ruby hello.rb
- 文の終りは「改行」か「;」
- 1行コメントは「#」
- ブロックコメントは「=begin」「=end」で挟む
** オブジェクトを表示するメソッド [#b9e2aac5]
print "Hello World", "world" # 普通に表示
puts "Hello World, again" # 改行付で表示
p "Hello World 3" # オブジェクト型がわかるように表示
** 変数と定数について [#v14cccae]
- 変数:オブジェクトにつける名札
-- 英子文字か_で始まる
-- 予約語はなし(例:end)
x = 10
p x
- 定数:全部大文字、変更禁止
MY_EMAIL = ""
** オブジェクトとメソッドを理解しよう [#l718f0cb]
- オブジェクト指向型言語で使われる用語
-- オブジェクト:便利な命令が詰まったデータ型
-- メソッド:便利な命令
p "hello".length
** クラスとインスタンスを理解しよう [#hb365e5e]
- クラス:設計図
- インスタンス:実体化されたデータ
- [[公式リファレンス:http://www.ruby-lang.org/en/]]より標...
** 数値的オブジェクトの演算 [#g57e9f58]
- 分数
x = Rational(2, 3)
puts x
- 演算子:+ - * / % **
x = 5 ** 2 # 25
x = 5 % 2 # 1
x = Rational(2, 3) + Rational(5, 6) # 3/2
- %%&color(red){RationalメソッドはMacプリインストールRuby...
- &color(red){ruby 1.9.2では改善};
** 数値的なオブジェクトで使えるメソッド [#c9b4c266]
- 型変換
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
** 文字列オブジェクトを理解する [#ree415fa]
x = "hello" # 変数や特殊文字を展開
y = 'hello' # 展開しない
# 特殊文字:\n \t
- 変数の展開
name = "taguchi"
puts "my name is #{name}"
** 文字列オブジェクトのメソッド [#nc393247]
p "hello".length # 文字列の長さを表示
p "hello".upcase # 文字列を大文字で表示
p "hello".reverse # 文字列を逆順で表示
p "hello".index("o") # 任意の文字が何文字目にあるか表示
p "hello".include?("o") # 任意の文字が含まれるかどうか表示
- その他のメソッドは公式リファレンスのStringクラスを参照
** 破壊的メソッドとは? [#f5574e8b]
s = "hello"
s1 = s.upcase! # 「!」を付与すると「s」も「s1」で上書き
p s
p s1
** 配列オブジェクトを理解する [#hb78b93a]
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番目
** 配列オブジェクトを操作する [#sba5ca95]
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番目から挿入
** 配列オブジェクトの演算 [#ua423d56]
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を足した要素を表示(重複あり)
** 配列オブジェクトのメソッド [#e07d9c89]
a = [1, 5, 3, 4, 5, 4, 8]
p a.uniq # 重複値を取り除いて表示
p a.sort # 昇順にソートして表示
- 先頭と末尾の操作
-- unshift / push:追加
-- shift / pop 削除
p a.push(10) # 末尾に10を追加
** ハッシュオブジェクトを理解する [#n94fc922]
- ハッシュオブジェクト(連想配列)
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales["tanaka"]
** ハッシュオブジェクトのメソッド [#j7a074a5]
sales = {"tanaka"=>100, "taguchi"=>150, "taniguchi"=>300}
p sales.size # サイズを表示
p sales.empty? # 空であるか?
p sales.key?("tanaka") # キーがあるかどうか?
p sales.has_value?(222) # バリューがあるかどうか?
** 日付や時間に関するクラスとメソッド [#ya8bdb5b]
- 現在時刻
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メソッドを使おう [#a8760cd5]
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桁で表示(...
- 文字列を返す「sprintf」
z = sprintf("%s's score is %d\n", x, y)
p z
** if文で条件分岐をしよう [#l8a35645]
score = 85
if score >= 80 then # thenは省略可能
puts "great!"
elsif score >= 60
puts "so so..."
else
puts "not so great"
end
** if分の別の書き方を理解しよう [#l7293639]
- 簡略的な書き方
puts "great" if score >= 80
- 条件演算子 if ... else ...
# 条件式?真の時の値:偽の時の値
a = 50
b = 20
max = a > b ? a : b
p max
** 比較演算子 [#kd36a62b]
- 不等号/不等号:< > >= <= == !=
- 正規表現の文字列マッチング: =~
puts "match!" if /taguchi/ =~ "my name is taguchi"
# "my name is taguchi"に"taguchi"が含まれていれば"match!...
- 論理演算子: && ||
** case文による条件分岐を理解しよう [#k19540d7]
signal = "yellow"
case signal
when "red"
puts "stop!"
when "green", "blue" # 条件を複数指定可能
puts "go!"
when "yellow"
puts "caution!"
else
puts "signal is broken"
end
** timesメソッドによる繰り返し処理 [#s0876ec2]
- 繰り返し処理
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による繰り返し処理 [#tfde8670]
- for文
users = ["taguchi", "fkoji", "dotinstall"]
for user in users do
puts user
end
- each文
users = ["taguchi", "fkoji", "dotinstall"]
users.each do |user|
puts user
end
- 実行結果
taguchi
fkoji
dotinstall
- for文(単純繰り返し)
users = ["taguchi", "fkoji", "dotinstall"]
for i in 1..10 do
puts i
end
- 実行結果
1
2
3
4
5
6
7
8
9
10
** ハッシュオブジェクトと繰り返し処理 [#ed6d8f32]
- each文を使ったハッシュオブジェクトの繰り返し表示処理
scores = {"taguchi"=>200, "fkoji"=>300, "dotinstall"=>1...
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文による繰り返し処理 [#cac0b679]
- while文(自己代入)
i = 1
while i < 10
puts i
# i = i + 1
i += 1 # 自己代入文
end
- 実行結果
1
2
3
4
5
6
7
8
9
** メソッドを定義しよう [#d5907f12]
# メソッドの定義
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~
** メソッドの引数、返り値について [#ie05008c]
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
- %%&color(red){上記の通りfor文をネストしたメソッドの引数...
- &color(red){ruby 1.9.2では改善};
** クラス作成&インスタンス化 [#gcceccda]
# クラス作成
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.damage
slime.damage
- 実行結果
slime appeared. His hp is 166
slime's hp is now 151
slime's hp is now 133
ページ名: