LoginSignup
28
24

More than 5 years have passed since last update.

getter/setterがないインスタンス変数に外部からアクセスする

Posted at
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

class Hoge
  # setterは公開されていない
  attr_reader :fuga
  def initialize
    @fuga = 'fuga'
    # getter/setter共に公開されていない
    @hige = 'hige'
  end
end

hoge = Hoge.new
p hoge.fuga
#  => "fuga"

# インスタンス変数の名前を文字列で指定して
# 外から強制的に書き換える
name = "@fuga"
hoge.instance_variable_set(name, 'fugafuga') if hoge.instance_variable_defined?(name)
p hoge.fuga
#  => "fugafuga"

# シンボルでも指定できる
hoge.instance_variable_set(:@fuga, 'fugafugafuga') if hoge.instance_variable_defined?(:@fuga)
p hoge.fuga
#  => "fugafugafuga"

# 読むのも当然できる
p hoge.instance_variable_get('@hige') if hoge.instance_variable_defined?('@hige')
#  => "hige"

28
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
24