2014-12-15 4 views
2

저는 루비를 처음 사용합니다. 내가 신발을 시도하고 여러 번 기능 보았다 이런 식으로 호출함수를 최종 매개 변수로 전달

somefunc "someparameter", "otherparameter" do 
    SomeFunctionContents 
end 

어떻게 같은 방식으로, 최종 인수와 같은 함수를받는 함수를 만들 수 있습니까? 나는 같이 호출 할 수 있도록하고 싶습니다 :

myFunction "myParameter" do 
    SomeStuffIWouldLikeToCallInMyFunction 
end 

내가 이것을 어떻게 달성 할 것인가?

내 시도가 지금까지왔다 : 단순히 작동하지 않습니다

def myfunc parameterone 
    doStuff 
    yield # In order to call the function passed after parameteone 
    doStuff 
end 
# AND LATER 
myfunc "parameterone" def 
    myFuncStuff 
end 

. 내 문제가 해결되었지만이 같은 실수를 사람들에게 도움이 될 수 있으므로

편집 는 명확성을 위해 나는 오류 메시지를 제공합니다.

syntax error, unexpected keyword_def, expecting end-of-input 
+3

마지막 예제에서 왜 'def'를 사용하지만 이전 질문에서'do'입니까? 다른 모든 것은 괜찮아 보입니다. – tadman

+0

와우. 그게 내 모든 실수 였어. 고맙습니다, 고쳐 주셨습니다. 나는 항상'def'를 사용하고 있는데, 적절한 구문이'do'라는 것을 잊어 버렸습니다. –

답변

2

블록을 호출합니다. 인수없이 Proc.new 호출 또한

def call_this_block 
    stuff = 'can be anything' 
    yield stuff 
end 

call_this_block { |x| 
    puts 'you can use brackets' 
    puts x 
} 

call_this_block do |x| 
    puts 'or you can use do/end blocks' 
    puts x 
end 

은, 당신의 실수가 def가하는 일의 오해 낳는다 생각 통과 블록

def call_this_block 
    Proc.new.call(111) 
end 

call_this_block { |x| x ** 3 } 

를 에뮬레이트합니다. 루비에는 메소드와 익명 함수가 있습니다. 비록 사촌과 비슷하지만 그것들은 동일하지 않습니다.

# def defines a method a attaches it to the current scope 
def this_method 
    puts 'asdf' 
end 

# this method is "attached" so you can retrieve it at any time and even redefine it 
method(:this_method) 
=> #<Method: Object#this_method> # Object is the default scope where you are sitting 

# call it 
method(:this_method).call 
this_method 

# this one of the many available syntaxis to create anonym functions or methods 
that_method = -> { puts 'is not attached' } 
that_method.call 
2

@nicooga는 Ruby에서 블록이라고 불렀습니다. "block_given?"을 사용할 수 있습니다. 블록이 호출 된 다음 함수를 호출 할 때 함수에 전달되었는지 감지합니다.

def sayHello 
    puts "hello" 
    if block_given? 
    yield 
    end 
    puts "hello again" 
end 

# pass a block to it 
sayHello do 
    puts "(exectute some task)" 
end 

# don't pass a block to it 
sayHello 
관련 문제