Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Created January 6, 2014 14:58
Show Gist options
  • Save justincampbell/8283945 to your computer and use it in GitHub Desktop.
Save justincampbell/8283945 to your computer and use it in GitHub Desktop.
def reset
Object.send :remove_const, 'Person'
end
# Inheriting from struct
class Person < Struct.new(:first_name, :last_name)
def full_name
[first_name, last_name].compact.join(' ')
end
end
Person.ancestors # => [Person, #<Class:0x007fa2cb8c8230>, Struct, Enumerable, Object, Kernel, BasicObject]
justin = Person.new("Justin", "Campbell") # => #<struct Person first_name="Justin", last_name="Campbell">
justin.full_name # => "Justin Campbell"
reset
# Struct with block
Person = Struct.new(:first_name, :last_name) do
def full_name
[first_name, last_name].compact.join(' ')
end
end
Person.ancestors # => [Person, Struct, Enumerable, Object, Kernel, BasicObject]
justin = Person.new("Justin", "Campbell") # => #<struct Person first_name="Justin", last_name="Campbell">
justin.full_name # => "Justin Campbell"
reset
# Class with attr_accessor (equivalent to Struct)
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
self.first_name = first_name
self.last_name = last_name
end
def full_name
[first_name, last_name].compact.join(' ')
end
end
Person.ancestors # => [Person, Object, Kernel, BasicObject]
justin = Person.new("Justin", "Campbell") # => #<Person:0x007fa2cb8c62c8 @first_name="Justin", @last_name="Campbell">
justin.full_name # => "Justin Campbell"
reset
# Class with attr_reader (immutable)
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
[first_name, last_name].compact.join(' ')
end
end
Person.ancestors # => [Person, Object, Kernel, BasicObject]
justin = Person.new("Justin", "Campbell") # => #<Person:0x007fa2cb8c5828 @first_name="Justin", @last_name="Campbell">
justin.full_name # => "Justin Campbell"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment