2014-09-25 3 views
3

당신이 두 가지 형태의 기능을 지정할 수 있습니다 array.each를 사용하여 :'do'키워드 구문을 사용하여 익명 함수를 허용하는 함수를 만드는 방법은 무엇입니까?

중괄호 :

a = [1,2,3] 
a.each { |x| puts x * x } 

출력 :

1 
4 
9 
=> [1, 2, 3] 

'할'구문 :

a = [1,2,3] 
a.each do |x| 
    puts (x * x) 
end 

출력 :

1 
4 
9 
=> [1, 2, 3] 

질문 : 가 어떻게 내 자신의 사용자 정의 기능과 함께 '할'구문 스타일을 복제 할 수 있습니까? 내가 얻을 수있는 중괄호 스타일에 가장 가까운입니다

내가 무엇을 시도했다 :

def PutWith2Arg(proc) 
    puts proc.call(2) 
end 

PutWith2Arg(Proc.new { |x| x + 100 }) 

출력 :

102 
=> nil 

답변

5

do |foo| … end{ |foo| … } 구문이 동일합니다. 이들은 Ruby에서 '블록'이며, 어떤 방법으로도이를 얻을 수 있습니다. 를 호출하려면 당신이 필요로 다음 중 하나

def my_method    # No need to declare that the method will get a block 
    yield(42) if block_given? # Pass 42 to the block, if supplied 
end 

my_method do |n| 
    puts "#{n} times 2 equals #{n*2}" 
end 
#=> "42 times 2 equals 84" 

my_method{ |n| puts "#{n} times 2 equals #{n*2}" } 
#=> "42 times 2 equals 84" 

my_method # does nothing because no block was passed 

또는, 더 정교한 용도 : 다른 방법에 블록을 통과해야 할 때

def my_method(&blk) # convert the passed block to a Proc named blk 
    blk.call(42) if blk 
end 

# Same results when you call my_method, with or without a block 

후자의 스타일이 유용합니다. 당신이 변수에 의해 참조되는 PROC 또는 람다이있는 경우, & 구문을 사용하는 방법에 대한 블록 등의 방법으로 전달할 수 있습니다 자세한 내용은 this webpage 상당히 유익하다

def my_method(&blk) # convert the passed block to a Proc named blk 
    [1,2,3].each(&blk) # invoke 'each' using the same block passed to me 
end 
my_method{ |x| p x=>x**2 } 
#=> {1=>1} 
#=> {2=>4} 
#=> {3=>9}  

.