Report abuse

Revised from RBP Tip #8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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)