Created
October 17, 2012 02:27
-
-
Save mizoR/3903375 to your computer and use it in GitHub Desktop.
インスタンス変数に値を入れるときは @attr よりも self.attr しておいた方がいい気がした
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ ~ cat ex.rb | |
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
class C | |
attr_accessor :password, :secret | |
def password=(pw) | |
@password = pw | |
@secret = @password.reverse | |
end | |
def call(pw) | |
@password = pw | |
p [self.password, self.secret] | |
self.password = pw | |
p [self.password, self.secret] | |
end | |
end | |
C.new.call('password') | |
➜ ~ ruby ex.rb | |
["password", nil] | |
["password", "drowssap"] |
👍
目から鱗
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
基本的には、インスタンス変数
@attr
への 値の設定は、def attr=(..)
の責任と考えて、クラス内からの値の設定の場合でも、ゲッタメソッドを使う方が無難な気がした。