[Ruby] LEVEL 2 Methods and Classes
Optional Arguments
Set default arguments, when we don't need to call it, we can simply skip it.
def new_game(name, year=nil, system=nil) { name: name, year: year, system: system } end game = new_game("Street Figher II")
Options Hash Argument
Sometimes, optinal argumetns also not that good. For exmaple, we have one argument added to the end, if we do want pass in reply_id and year, system we don't need to pass in, then we need to put placeholder in the function call.
def new_game(name, year=nil, system=nil, reply_id = nil) { name: name, year: year, system: system } end game = new_game("Street Figher II", nil, nil, 50)
Therefore we can use options has argument:
def new_game(name, options={}) { name: name, year: options[:year], system: options[:system] } end game = new_game("Street Figher II", year: 1992, system: "SNES")
Exception
def get_tweet(list) unless list.authorized?(@user) raise AuthorizationException.new end list.tweets end #raise an Exception instead begin tweets = get_tweets(my_list) rescue AuthorizationException warn "You are not authorized to access this list" end