LoginSignup
1
0

More than 3 years have passed since last update.

attr_readerについて

Posted at

 以下のコードにつき、rubocop -aを実行したところ、修正を頂戴しました。

app/helpers/question_helper.rb
class AddQuestion

  def initialize(a,b)
    @text = "#{a} + #{b}" 
    @answer = a + b
  end

# rubocop -a 実行前 -------------------------------   
  def text # ゲッター
    @text
  end

  def answer # ゲッター
    @answer 
  end
# rubocop -a 実行前 -------------------------------

# rubocop -a 実行後 -------------------------------
  attr_reader :text, :answer
# rubocop -a 実行後 -------------------------------  

end

 attr_readerとはなんだろうかと思い調べてみました。

クラスに設定したインスタンス変数の値を、インスタンスから読み取って表示するためだけに定義するメソッドをゲッターといい、attr_readerを用いてこれに代えることができるとのこと。
 
 なお、ここでは登場しないが、あるインスタンスが持つインスタンス変数の値を更新するためだけのメソッドのことをセッターといい、これはattr_writerで記述することができる。
 さらには、attr_accessorは両者を兼ねる。

  
 rubocop実行前後を見比べると勉強になります。

1
0
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
1
0