Leon's Blogging

Coding blogging for hackers.

Ruby - Attr_accessor vs Attr_writer vs Attr_reader

| Comments

快速在 Ruby 的類別裡產生一對 getter 以及 setter 方法

  • attr_accessor: attr_reader + attr_writer
  • attr_reader: def name; end
  • attr_writer: def name=(new_name); end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Animal
  attr_accessor :name

  def initialize
    @name = 'Dog'
  end
end


animal = Animal.new

animal.name
# => "Dog"
animal.name = 'Cat'
animal.name
# => "Cat"

相當於

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Animal
  def initialize
    @name = 'Dog'
  end

  # attr_reader
  def name
       @name
  end

  # attr_writer
  def name=(new_name)
       @name = new_name
  end
end

參考文件

Ruby 語法放大鏡之「attr_accessor 是幹嘛的?」

Comments