2010-03-04 2 views
15

저는 setter 역할을하는 메서드를 작성하려고하는데 할당 된 값 외에도 추가 인수가 필요합니다. 바보 예 :Ruby에서 추가 인수를 사용하는 setter 메서드 만들기

class WordGenerator 
    def []=(letter, position, allowed) 
    puts "#{letter}#{allowed ? ' now' : ' no longer'} allowed at #{position}" 
    end 

    def allow=(letter, position, allowed) 
    # ... 
    end 
end 

인덱서 작품으로 작성하고 내가 이런 식으로 호출 할 수 있습니다 : 나는 다음 중 하나를 시도 할 때

gen = WordGenerator.new 

gen['a', 1] = true 
# or explicitly: 
gen.[]=('a', 1, true) 

을하지만, 인터프리터는 불평 :

gen.allow('a', 1) = false # syntax error 
gen.allow=('a', 1, false) # syntax error 

왜이 작동하지 않습니다, 나는 분명한가 누락 되었습니까?

+0

관련/중복 : http://stackoverflow.com/questions/9280623/setter-method-assignment-with-multiple-arguments – kotique

답변

16

파서가 허용하지 않기 때문에 작동하지 않습니다. identifier = expression, expression.identifier = expression (식별자가 \w+ 인 경우), expression[arguments] = expressionexpression.[]= arguments과 같이 문자열이나 기호 또는 문자 리터럴 (?=)의 일부로 등호가 허용됩니다. 그게 전부 야.

gen.send(:allow=, 'a', 1, false)이 작동하지만 그 시점에서 메서드에 =이 포함되지 않은 이름을 지정할 수 있습니다.

+0

감사합니다. 재미있는 점은 'def seed = (value) end; gen.seed = (1) '. 나는 'seed ='가 식별자가 될 것으로 예상 했었지만, (당신의 규칙을 정확하게 이해한다면) [gen/expr]. [seed/identifier] = [(1)/expr]과 같이 나타납니다. 이것은 하나 이상의 인수로 실패하는 이유를 설명 할 것입니다 - (a) 표현이지만, (a, b)는 아닙니다! 이것을 가정하면 'gen. [] = ('a ', 1, true)'는 어떻게 작동합니까? –

+0

'. [] ='나는 위의 목록에서 잊어 버린 또 다른 특별한 경우입니다 (물론'expression [comma_seperated_expressions] = expression'과 함께 작동합니다). – sepp2k

6

나는 이것을 보았고 배열이나 해쉬로서의 나의 주장을 전달하기로 결정했다.

예컨대 :

def allow=(arguments) 
    puts arguments[:letter] 
    puts arguments[:position] 
    puts arguments[:allowed] 
end 

object.allow={:letter=>'A',:position=>3,:allowed=>true} 
관련 문제