Ruby基礎③
ループ処理
while
i = 0 while i < 10 do puts "#{i}: hello!" i += 1 end
出力結果
0: hello! 1: hello! 2: hello! 3: hello! 4: hello! 5: hello! 6: hello! 7: hello! 8: hello! 9: hello!
times
10.times do |i| puts "#{i}:hello" end #1行であれば省略記法が使用できる 10.times { |i| puts "#{i}:hello" }
出力結果
0:hello 1:hello 2:hello 3:hello 4:hello 5:hello 6:hello 7:hello 8:hello 9:hello
for
#数値 for i in 15..20 do p i end #配列 for color in ["red","blue"] do p color end #ハッシュ for name,score in {tanaka:200,suzuki:400} do puts "#{name}: #{score}" end
出力結果
15 16 17 18 19 20 "red" "blue" tanaka: 200 suzuki: 400
each
#数値 (15..20).each do |i| p i end #配列 ["red","blue"].each do |color| p color end #ハッシュ {tanaka:200,suzuki:400}.each do |name,score| puts "#{name}: #{score}" end
出力結果
15 16 17 18 19 20 "red" "blue" tanaka: 200 suzuki: 400
loop
i = 0 loop do p i i += 1 end
出力結果
0 1 2 3 4 . . . 無限ループ
break
#iが7になったら処理を中断する 10.times do |i| if i == 7 then break end p i end
出力結果
0 1 2 3 4 5 6
next
#iが7のときに処理をスキップする 10.times do |i| if i == 7 then next end p i end
出力結果
0 1 2 3 4 5 6 8 9
メソッド
メソッド基本
#基本形 def メソッド名 処理 最後の一行が戻り値 end #引数あり def メソッド名(引数名) 処理 end #引数あり+引数デフォルト値設定 def メソッド名(引数名 = デフォルト値) 処理 end
def sayHi(name = "suzuki") puts "hi!#{name}" return "hi!#{name}" end sayHi "tanaka" sayHi p sayHi
出力結果
hi!tanaka hi!suzuki hi!suzuki "hi!suzuki"
クラス
クラス基本
class クラス名 def initialize(引数名) @変数 = 引数名 #以降@変数をクラス内各メソッドで使用できる end end #呼び出し 変数 = クラス名.new(引数)
class User #アクセサー attr_accessor :name # attr_reader :name # setter: name=(value) # getter: name def initialize(name) @name = name end def sayHi # self # self.name => @name #引数が1つの場合はselfも省略できる puts "hi!! i am #{@name}" puts "hi!! i am #{self.name}" puts "hi!! i am #{name}" end end tom = User.new("tom") tom.name = "tom Jr." p tom.name tom.sayHi bob = User.new("bob") bob.sayHi # レシーバー
出力結果
"tom Jr." hi!! i am tom Jr. hi!! i am tom Jr. hi!! i am tom Jr. hi!! i am bob hi!! i am bob hi!! i am bob
クラスメソッド・クラス変数・定数
class User @@count = 0 #クラス変数(@@を先頭につける) VERSION = 1.1 #クラス定数(全て大文字) def initialize(name) @@count += 1 @name = name end def sayHi puts "hi! i am #{name}" end def self.info #クラスメソッド puts "#{VERSION}: User Class, #{@@count} instances." end end tom = User.new("tom") bob = User.new("bob") steve = User.new("steve") User.info #クラスメソッドにアクセス p User::VERSION #定数にアクセス
出力結果
1.1: User Class, 3 instances. 1.1
参考になりそうな記事 qiita.com
クラスの継承
class User def initialize(name) @name = name end def sayHi puts "hi! i am #{@name}" end end # User: 親クラス、Super Class # AdminUser: 子クラス、Sub Class #クラスの継承には「<」を用いる class AdminUser < User def sayHello puts "Hello from #{@name}" end #同じメソッド名をつけることでオーバーライド def sayHi puts "hi! from admin!" end end tom = AdminUser.new("tom") tom.sayHi tom.sayHello
出力結果
hi! from admin! Hello from tom