悪いコードというか、普通のクラス。
class Vehicle
VALUES = ["BUS", "BIKE"]
attr_accessor :name
def initialize(name)
@name = name
end
def start_bus?
self.name == "BUS"
end
def start_bike?
self.name == "BIKE"
end
end
v = Vehicle.new("BUS")
puts v.start_bus?
puts v.start_bike?
define_methodを使って実装する。
class Vehicle
VALUES = ["BUS", "BIKE"]
attr_accessor :name
def initialize(name)
@name = name
end
VALUES.each do |value|
define_method "start_#{value.downcase}?" do
self.name == value
end
end
end
v = Vehicle.new("BUS")
puts v.start_bus?
puts v.start_bike?
0 件のコメント:
コメントを投稿