I am doing 'ruby bits' course on codeschool, and starting to hate it a bit. Assignments require knowledge which was not covered in their short lectures, which forces me to google. Sometimes I don't even know the search terms needed. Can anyone help me to understand what's going on in the code below?
class InvalidGameError < StandardError; end
def new_game(name, options={})
raise InvalidGameError, "You must provide a name for this 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
I don't quite understand what's happening in the first line. Also why the begin statement needed? Isn't the fourth line enough?
The first line is equivalent to
class InvalidGameError < StandardError
end
which is the common Ruby way to define a new exception. In this case, you define an InvalidGameError
exception that inherits from StandardError
.
The begin/rescue/end
block is the Ruby exception handling mechanism .
If any InvalidGameError
will be raised during the execution of the code between the begin/rescue
, Ruby will execute whatever code is after the rescue
.
begin
# do something
rescue StandardError
# do something if the error occurs
end
The first line is defining a new Exception which is how object oriented programming languages handle runtime errors. In this case the only reason your instructor is defining a new exceptions is so that when you read the code you know exactly what error is being handled. You could have just used StandardError directly but InvalidGameError is a better name for the error the code is handling. So let's take the code you posted for an example: The method new_game requires the user to provide a name, and if you try to call it with a name that's set to nil or false (new_game(nil, {year: 2015, system: "xbox"})) your code will raise an exceptions which will stop and exit the program otherwise the method returns a hash that has three pairs: a name key with its value set to the name you provided as a parameter, a year key with its value set to the year key of the options hash and a system key with its value set to the system key of the options hash.
I know, its confusing but this code uses some concept that your really need to know before you can understand it, namely: Exception Handling, Hashes and Conditionals and Ruby objects truth values
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.