@Konboi memo

主に技術に関してつらつらと。

今更ながらatter_reader,writer,accesor の復習

class Hoge
  attr_reader :read
  attr_writer :write
  attr_accessor :access

  def initialize(read, write, access)
    @read   = read
    @write  = write
    @access = access
  end

  def access_update
    @access = @write
  end
end

hoge = Hoge.new('read', 'write', 'access')

puts hoge.read
puts hoge.access

hoge.access_update
puts hoge.access


hoge.write = 'write2'
hoge.access_update
puts hoge.access

hoge.access = 'boooo'
puts hoge.access

# 以下エラーになる
hoge.read = 'fugafuga'
hoge.write = 'write3'
# 実行結果
read
access
write
write2
boooo
atter.rb:35:in `<main>': undefined method `read=' for #<Hoge:0x007f9566752288> (NoMethodError)
  • attr_reader は iniializeで設定したとき以外値の変更はできない。
  • attr_writer は 値をそとから変更できるけど、外から呼び出しはできない
  • attr_accessor は外から読み込み、書き込みできる。

パーフェクトRuby (PERFECT SERIES 6)

パーフェクトRuby (PERFECT SERIES 6)