# Thanks Fabian Streitel for pointing out that the previous# example does not allow setting name to nil or false#classPersondefname(*args)return@nameif args.empty?@name= args.firstendalias_method:name=, :nameend# 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_evaldo
name "Gregory Brown"
puts name
end# Without the optional argument to name(), we'd be stuck with:Person.new.instance_evaldoself.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)