[Ruby] LEVEL 2 Methods and Classes -- Ex
Optional Arguments
We'll store a little more information about our games than just the name. Optional arguments are important for a flexible interface. Let's change our new_game
method so it can be called without passing in year
or system
.
def new_game(name, year, system) { name: name, year: year, system: system } end game = new_game("Street Figher II", nil, nil)
Answer:
def new_game(name, year=nil, system=nil) { name: name, year: year, system: system } end game = new_game("Street Figher II")
Options Hash Argument
Defaulting two arguments to nil
isn't ideal. Update the method signature and implementation to take an optional options
hash with keys for :year
and :system
.
def new_game(name, year=nil, system=nil) { name: name, year: year, system: system } end game = new_game("Street Figher II", "SNES", 1992)
Answer:
def new_game(name, options={}) { name: name, year: options[:year], system: options[:system] } end game = new_game("Street Figher II", year: 1992, system: "SNES")
Raise Exception
We want to make sure that each game is a valid game object - in this case a simple hash of values. Even still, we wouldn't want to return a hash with a nil
name. Raise an InvalidGameError
error in the new_game
method if name is nil.
class InvalidGameError < StandardError; end def new_game(name, options={}) { name: name, year: options[:year], system: options[:system] } end begin game = new_game(nil) rescue InvalidGameError => e puts "There was a problem creating your new game: #{e.message}" end
Answer:
class InvalidGameError < StandardError; end def new_game(name, options={}) raise InvalidGameError, "You must provide a name for the game" unless name { name: name, year: options[:year], system: options[:system] } end begin game = new_game(nil) rescue InvalidGameError => e puts "There was a problem creating your new game: #{e.message}" end
Splat Arguments
When passing in an array of arguments to a method, sometimes it'll make sense to use Ruby's "splat" operator rather than explicitly requesting an array. Update the describe_favorites
method and the call to it to instead use the splat operator.
def describe_favorites(*games) for game in games puts "Favorite Game: #{game}" end end describe_favorites(['Mario', 'Contra', 'Metroid'])
Answer:
def describe_favorites(*games) for game in games puts "Favorite Game: #{game}" end end describe_favorites('Mario', 'Contra', 'Metroid')
Class
Passing around hashes is getting troublesome, let's use a class to hold our data. We've started the Game class for you, now please implement the initialize method to store name, system and year in instance variables.
class Game def initialize(name, options={}) end end
Answer:
class Game def initialize(name, options={}) @name = name @year = options[:year] @system = options[:system] end end
attr_accessor
Whoever created the game object will want to be able to access the name
, year
and system
for the game, but that doesn't mean we need to make getter
methods for them. Refactor the code below to make these variables available using the Ruby way with attr_accessor
.
class Game def initialize(name, options={}) @name = name @year = options[:year] @system = options[:system] end def name @name end def year @year end def system @system end end
Answer:
class Game attr_accessor :year, :system, :name def initialize(name, options={}) @name = name @year = options[:year] @system = options[:system] end end
attr_reader
When a game is initialized, store another variable called created_at
which is set to Time.now
in the initialize method. Make sure it can be accessed, but that it cannot be set from outside the object.
class Game attr_accessor :name, :year, :system def initialize(name, options={}) @name = name @year = options[:year] @system = options[:system] end end
Answer:
class Game attr_accessor :name, :year, :system attr_reader :created_at def initialize(name, options={}) @name = name @year = options[:year] @system = options[:system] @created_at = Time.now end end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具