Skip to content

Instantly share code, notes, and snippets.

@yaotti
Created July 31, 2011 04:37
Show Gist options
  • Save yaotti/1116402 to your computer and use it in GitHub Desktop.
Save yaotti/1116402 to your computer and use it in GitHub Desktop.
#ruby でobject.fieldを得るときに,objectがnilのときはnilを返して,そうでないときはobject.fieldを返すようなメソッドってあるのかな.NilClass.instance_methodsを見たけどそれらしいものはなかった
class User
attr_accessor :name
def initialize name=nil
self.name = name
end
end
me = User.new 'me'
p me.name.length # => 2
unknown = User.new
p unknown.name.length # => error!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment