Last active
August 29, 2015 14:05
-
-
Save mudge/2914 to your computer and use it in GitHub Desktop.
Add a "name" accessor to objects with first_name and last_name fields.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Nameable | |
# Assuming first_name and last_name are accessors. | |
def name=(name) | |
self.first_name, *_, self.last_name = name.split | |
end | |
def name | |
[first_name, last_name].compact.join(" ") | |
end | |
end | |
class Monkey | |
include Nameable | |
attr_accessor :first_name, :last_name | |
end | |
m = Monkey.new | |
m.name = "Robert Horatio Paulson" | |
m.first_name #=> "Robert" | |
m.last_name #=> "Paulson" | |
m.name #=> "Robert Paulson" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment