首页 > 其他 > 详细

[Ruby] LEVEL 2 Methods and Classes

时间:2015-11-02 06:37:36      阅读:247      评论:0      收藏:0      [点我收藏+]

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

 

[Ruby] LEVEL 2 Methods and Classes

原文:http://www.cnblogs.com/Answer1215/p/3980544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!