使用ruby ver 2.3.3p222
ミニツク解いてみる
演習1
class Book
def initialize(hash)
@title = hash[:title]
@author = hash[:author]
hash[:library] << self
end
def to_s
"Title: #{@title}, Author:#{@author}"
end
end
class Library
def initialize
@arg = []
end
def <<(arg)
@arg << arg
end
def to_s
puts "Library Contents:"
@arg.join("\n")
end
end
my_library = Library.new
Book.new(:author => "Herman Melville", :title => "Moby-Dick", :library => my_library)
Book.new(:author => "Hans Christian Andersen", :title => "The Ugly Duckling", :library => my_library)
puts my_library
# result
# Library Contents:
# Title: Moby-Dick, Author:Herman Melville
# Title: The Ugly Duckling, Author:Hans Christian Andersen
演習2
使用しているversionではstringクラスにto_aメソッドがなく解答例ではエラーした。
def clever_print(*arg)
puts arg.map { |i| i.is_a?(Hash) ? i.to_a : i }.join(" ")
end
clever_print(["Ruby"], "the", ["Programming", "Language"])
clever_print(["Agile", "Web", "Development"], "with", { :Rails=>3.0 })
# result
# Ruby the Programming Language
# Agile Web Development with Rails 3.0
演習3
module Mail
# インスタンス変数を読み出すためのアクセサメソッド
attr_reader :sender, :recipient
def write(arg)
@write = arg
end
def to_s
arr = []
arr << "Postcard of #{@time}:"
arr << ""
arr << "Dear #{@recipient},"
arr << ""
arr << "#{@write},"
arr << ""
arr << "Sincerely,"
arr << "#{@sender}"
puts arr.join("\n")
end
def send
@time = Time.now
puts "#{@time} Sending a #{self.class} to #{self.recipient}"
end
end
class Postcard
include Mail
def initialize(sender, recipient)
@sender, @recipient = sender, recipient
end
end
card = Postcard.new("Me", "Friend")
card.write("Did you forget my birthday?")
card.send
puts "-" * 60
sleep(2)
puts card
# result
# 2018-06-30 16:15:58 +0900 Sending a Postcard to Friend
# ------------------------------------------------------------
# Postcard of 2018-06-30 16:15:58 +0900:
#
# Dear Friend,
#
# Did you forget my birthday?,
#
# Sincerely,
# Me
# #<Postcard:0x007f9313040af8>
演習4
解答のまんま
class Planet
def life?
puts "Who knows?"
end
end
pluto = Planet.new()
earth = Planet.new()
mars = Planet.new()
# 特異メソッド
def pluto.life?
puts "Probably not."
end
def earth.life?
puts "Positively!"
end
pluto.life?()
earth.life?()
mars.life?()
### result
# Probably not.
# Positively!
# Who knows?
演習5
def buy_tickets(*arg)
if 0 < arg.count && arg.count < 4
arg.each do |i|
puts "Buying a ticket for #{i}"
end
else
puts "Buying a group ticket for #{arg.join(", ")}."
end
end
buy_tickets("Sam", "Dave", "David")
buy_tickets("John", "Paul", "Ringo", "George")
# result
# Buying a ticket for Sam
# Buying a ticket for Dave
# Buying a ticket for David
# Buying a group ticket for John, Paul, Ringo, George.
演習6
class Tool
def use
puts "Picks up #{@color} #{self.class.to_s}"
end
def initialize(color)
@color = color
end
end
class Hammer < Tool
def use
super
puts "Bam bam bam"
end
end
Hammer.new('red').use
# result
# Picks up red Hammer
# Bam bam bam