2013-07-19 5 views
0

내 코드의 기호는 class_eval 섹션에 있습니다. 이것은 내게 외국적이다. 그것은 무엇을 의미 하는가?# 기호의 의미

다음 코드는 class_eval에 #을 가지고 왜
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{ 
def #{attr_name}=(attr_name) 
@#{attr_name} = attr_name 
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil? 
@#{attr_name}_history << attr_name 
end 
} 
    end 
end 

답변

2
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에 보내기 전에 성공적으로 수행합니다.

+0

좋아요! 고마워요 :) – Howarto

+0

아니 prob, 친구. 다행 이군. – Doodad

2

은?

이것은 문자열 보간법입니다.

하나의 예 : 당신의 앞에 백 슬래시를 넣어의 string.Instead 더 인용 문자가있을 때이 두 번 인용 문자열에 대한 대안입니다 Here

x = 12 
puts %Q{ the numer is #{x} } 
# >> the numer is 12 

%의 Q 그들.

+1

http://kconrails.com/2010/12/08/ruby-string-interpolation/는 나머지 코드를 놓친 않다면 단지 이상한 루비 곳처럼 보이기 때문에, 무엇을 '%의 Q' 내가 생각도하고있다 언급 할 가치가 –

4

이 기능을 문자열 보간이라고합니다. 실제로 효과가있는 것은 #{attr_name}attr_name 실제 값으로 대체 한 것입니다. 게시 한 코드는 런타임에서 일반 이름의 변수를 사용하려는 경우 중 하나를 보여줍니다.

그런 다음 더 자주 사용하는 경우이다 사용 "Hello, #{name}!"#{name}가 자동으로 여기에 대체 될 것이다 -이 매우 편리한 기능입니다 : 당신은 문자열이 방법을 사용할 수 있습니다

. 통사론 설탕.

코드에있는 %Q 참고 -이 코드는 다음 코드를 문자열로 변환하고 나중에 class_eval으로 전달되어 거기에서 실행됩니다. 그것에 대해 더 자세히보기 here. 그것 없이는 작동하지 않을 것입니다.

+2

보간은 혼란의 지점이 될 수 있습니다 어디서나 발생할 수 –