Skip to content

Instantly share code, notes, and snippets.

@udzura
Last active May 8, 2021 14:23
Show Gist options
  • Save udzura/4865e8dcadbc26d64318136e4c34cbe8 to your computer and use it in GitHub Desktop.
Save udzura/4865e8dcadbc26d64318136e4c34cbe8 to your computer and use it in GitHub Desktop.
問Y-1
クラス(モジュール)にはancestorsという、そのクラスの親を一覧するメソッドがあります。以下のインスタンスについて、その所属するクラスのancestorsを表示してください。
・String 例: "aaa"
・Array 例: [1, 2, 3]
・自作のクラス
また、これらに共通するクラス/モジュールを表示してください
問Y-2
1) 地下鉄の「路線を表すクラス」「駅を表すクラス」を考えて、コードで表してください。
2) これらのインスタンスを、「福岡市営地下鉄空港線」を例に作成してください。
3) この二つのクラス(とRubyの標準クラス)を使い「駅Aから駅Bを与えたら、何駅かかるか答える」メソッド show_distance を「路線を表すクラス」に実装してください。```
問Y-3
1) 以下のクラスの継承関係を考えて、コードで表してください。
Animal, Mammal, Bird, Fish, Dog, Bulldog, Shiba, Whale, Chicken, Quail, Salmon, Sardine
2) また、それぞれのクラスに以下のインスタンスメソッドを実装し、true/falseを返してください。継承を使いなるべく少ない記述にしましょう
* has_backbone?  # 背骨があればtrue
* laying_eggs?    # 卵を産めばtrue
* thermostatic?  # 恒温動物であればtrue
* aquatic?           # 水生生物であればtrue
p "aaa".class.ancestors
p [1, 2, 3].class.ancestors
require_relative "Y-3" # 手抜き。笑
p Animal.ancestors
p Shiba.ancestors
puts "Common ones:"
p "aaa".class.ancestors & [1, 2, 3].class.ancestors & Animal.ancestors
class Line
def initialize(name:)
@name = name
@stations = []
end
attr_reader :name
def add_station(num, name)
@stations << Station.new(num: num, name: name)
@stations.sort!{|s| s.num }
end
def show_distance(sta_a, sta_b)
from = @stations.find{|s| s.name == sta_a }
to = @stations.find{|s| s.name == sta_b }
"%s 駅" % (to.num - from.num).abs
end
end
class Station
def initialize(num: ,name:)
@num, @name = num, name
end
attr_reader :num, :name
end
line = Line.new(name: "福岡市営地下鉄空港線")
# Data from outer
[
[1, "姪浜"],
[2, "室見"],
[3, "藤崎"],
[4, "西新"],
[5, "唐人町"],
[6, "大濠公園"],
[7, "赤坂"],
[8, "天神"],
[9, "中洲川端"],
[10, "祇園"],
[11, "博多"],
[12, "東比恵"],
[13, "福岡空港"],
].each do |num, name|
line.add_station(num, name)
end
puts line.show_distance("福岡空港", "博多")
puts line.show_distance("西新", "天神")
class Animal
def has_backbone?
true
end
def laying_eggs?
true
end
def thermostatic?
false
end
def aquatic?
true
end
end
class Mammal < Animal
def laying_eggs?
false
end
def thermostatic?
true
end
def aquatic?
false
end
end
class Bird < Animal
def thermostatic?
true
end
def aquatic?
false
end
end
class Fish < Animal
end
class Dog < Mammal
end
class Bulldog < Dog
end
class Shiba < Dog
end
class Whale < Mammal
def aquatic?
true
end
end
class Chicken < Bird; end
class Quail < Bird; end
class Salmon < Fish; end
class Sardine < Fish; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment