DEV Community

dss99911
dss99911

Posted on Originally published at dss99911.github.io

Ruby 블록과 Lambda

Ruby의 블록(Block)과 Lambda에 대해 알아봅니다.

블록 (Blocks)

블록은 메서드 호출과 함께 코드 블록을 전달하는 방법입니다.

기본 사용법

def call_block
  puts 'Start of method'
  yield
  yield
  puts 'End of method'
end

call_block { puts 'In the block' }
Enter fullscreen mode Exit fullscreen mode

파라미터가 있는 블록

def call_block
  yield('hello', 99)
end

call_block { |str, num| puts str + ' ' + num.to_s }
Enter fullscreen mode Exit fullscreen mode

블록 존재 여부 확인

def try
  if block_given?
    yield
  else
    puts "no block"
  end
end

try                        # "no block"
try { puts "hello" }       # "hello"
try do puts "hello" end    # "hello"
Enter fullscreen mode Exit fullscreen mode

블록을 통한 반복

x = 10
5.times do |x|
  puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"
Enter fullscreen mode Exit fullscreen mode

Lambda

Lambda는 익명 함수를 만드는 방법입니다.

기본 사용법

prc = lambda { puts 'Hello' }
prc.call

# 여러 줄 Lambda
toast = lambda do
  'Cheers'
end
puts toast.call
Enter fullscreen mode Exit fullscreen mode

Lambda를 메서드 파라미터로 전달

def some_mtd(some_proc)
  puts 'Start of mtd'
  some_proc.call
  puts 'End of mtd'
end

say = lambda do
  puts 'Hello'
end

some_mtd(say)
Enter fullscreen mode Exit fullscreen mode

파라미터가 있는 Lambda

a_Block = lambda { |x| "Hello #{x}!" }
puts a_Block.call('World')  # "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Originally published at https://dss99911.github.io

Top comments (0)