Ruby復習3【W:67.8kg】

=begin
Ruby学習 class作成
=end


################################################################################
# クラス
class HelloWorld

@@count = 0

################################################################################
#initializeメソッド
def initialize(myname = "Ruby")
@name = myname #インスタンス変数初期化
end


################################################################################
#アクセスメソッド(参照)
def name
return @name
end


################################################################################
#アクセスメソッド(変更)
def name=(value)
@name = value
end


################################################################################
#アクセスメソッド定義
attr_accessor :name #参照、更新
attr_writer :name #更新
attr_reader :name #参照


################################################################################
#インスタンスメソッド
def hello
print "Hello World. I am " + @name + "\n"
@@count += 1
end


################################################################################
#クラスメソッド
def self.hello(name)
print name , " said hello. \n"
end


################################################################################
#クラス変数
def self.count
@@count
end


################################################################################
#定数
Version = "1.0"

end


################################################################################
#使用方法
bob = HelloWorld.new("Bob")

#インスタンスメソッド
bob.hello()

#アクセスメソッド
bob.name = "Ken"
bob.hello()

#クラスメソッド
HelloWorld.hello("Bob")

#定数
puts HelloWorld::Version

#クラス変数
puts HelloWorld.count



################################################################################
# 継承クラス
class RingArray < Array

################################################################################
# これ以降に定義したメソッドはpublic
public

def [](i)
idx = i % size
super(idx)
end


################################################################################
# これ以降に定義したメソッドはprivate
private

def TestMethod1
puts "TestMethod1"
end


################################################################################
# これ以降に定義したメソッドはprotected
protected

def TestMethod2
puts "TestMethod2"
end

end


################################################################################
# 使用方法
eto = RingArray["a","b","c"]

puts eto[0]
puts eto[1]
puts eto[2]
puts eto[3]
puts eto[4]
puts eto[5]



=begin
Ruby学習 例外処理
=end

################################################################################
# 例外処理
begin
#処理


#例外を発生させる
raise Exception::StandardError::IOError,"例外が発生しました。"


rescue => ex #例外が起こった場合の処理
puts ex.class #例外の種類
puts ex.message #例外のメッセージ
puts ex.backtrace #例外の発生した位置に関する情報


puts $! #最後の発生した例外
puts $@ #最後に発生した例外の位置に関する情報


#retryを実行すると、begin以下の処理をやり直すことができる


ensure #例外の有無に関わらず必ず実行する処理
puts "後処理を実行"
end