## Revised from RBP Tip #8
# Thanks Fabian Streitel for pointing out that the previous
# example does not allow setting name to nil or false
#
class Person
def name(*args)
return @name if args.empty?
@name = args.first
end
alias_method :name=, :name
end
# Works normally from the external interface
person = Person.new
person.name = "Gregory Brown"
puts person.name
# Looks nice from the inside as well:
Person.new.instance_eval do
name "Gregory Brown"
puts name
end
# Without the optional argument to name(), we'd be stuck with:
Person.new.instance_eval do
self.name = "Gregory Brown"
puts name
end
# Without the alias for name=, we'd be stuck with:
person = Person.new
person.name "Gregory Brown"
puts person.name
# You want to make sure to alias name= rather than just do attr_writer name, so as to not duplicate setter logic.
# (unless you intentionally want to make them different)