def #{attr_name}=(attr_name)
@#{attr_name} = attr_name
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history << attr_name
end
동등의이 "params"
을 말할 수 있도록 attr_name
변수합니다. 이는 실제로 다음과 같이 변형됩니다.
def params=(attr_name)
@params = attr_name
@params_history = [nil] if @params_history.nil?
@params_history << attr_name
end
왜 그런가? 문자열 보간이라고하는 것이 있습니다. 문자열에 #{something}
을 쓰면 something
이 평가되고 해당 문자열에서 바뀝니다.
문자열에 없는데 왜 위 코드가 작동합니까?
대답은입니다.
루비는 당신이 일을하는 다른 방법을 제공하고, 일부 리터럴에 대한 대체 구문이, 그게 그렇게 간다 : 당신이 동일하거나 대응을 폐쇄을 사용할 때 {}
만큼, 어떤 구분자가 될 수 %w{one two three}
. 따라서 %w\one two three\
또는 %w[one two three]
일 수 있습니다. 모두 작동합니다.
그 중 하나는 %w
입니다. 배열의 경우 %Q
은 큰 따옴표로 묶은 문자열을 나타냅니다.당신이 그들 모두를보고 싶어하면, 나는 당신이 한 번 봐 보시기 바랍니다 : http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
을 지금, 그 코드
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name # create the attribute's getter
attr_reader attr_name+"_history" # create bar_history getter
class_eval %Q{ <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # STRING BEGINS
def #{attr_name}=(attr_name)
@#{attr_name} = attr_name
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history << attr_name
end
} <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # STRING ENDS
end
end
에서 우리는 문자열 보간 전체 부분이 %Q{ }
안에 볼 수 있습니다. 즉, 전체 블록은 큰 따옴표로 묶인 문자열입니다. 그래서 String 보간법은 String을 eval에 보내기 전에 성공적으로 수행합니다.
좋아요! 고마워요 :) – Howarto
아니 prob, 친구. 다행 이군. – Doodad