Proc&Lamda

Proc

  • Procs are full-fledged objects, so they have all the powers and abilities of objects. (Blocks do not.)

  • Unlike blocks, procs can be called over and over without rewriting them. This prevents you from having to retype the contents of your block every time you need to execute a particular bit of code.

cube = Proc.new{ |x| x ** 3 }
[1, 2, 3].collect!(&cube)
# ==> [1, 8, 27]
[4, 5, 6].map!(&cube)
# ==> [64, 125, 216]

& is used to convert the cube proc into a block

  • .call ์„ ์ด์šฉํ•ด์„œ proc์„ ์‰ฝ๊ฒŒ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ๋‹ค.

    test = Proc.new { # does something }
    test.call
    # does that something!
  • convert symbols to procs using that handy little &

    strings = ["1", "2", "3"]
    nums = strings.map(&:to_i)
    # ==> [1, 2, 3]

Lambda

lambda { |param| block }
lambda { puts "Hello!" } == Proc.new { puts "Hello!" }

proc๊ณผ lambda์˜ ์ฐจ์ด

  1. argument ๊ฐ€ ์˜ค๋ฅ˜๊ฐ€ ๋‚ฌ์„๋•Œ proc์€ ๋ฌด์‹œํ•˜๊ณ  nil์ฒ˜๋ฆฌ ํ›„ ๋„˜์–ด๊ฐ€๋Š”๋ฐ lambda๋Š” ์˜ค๋ฅ˜๊ฐ€๋‚œ๋‹ค.

  2. lambda๋Š” call์ด ๋˜๋ฉด ๋‹ค์‹œ ๋งˆ์ง€๋ง‰ ์ฝ”๋“œ๋กœ ๋Œ์•„๊ฐ€๋Š”๋ฐ proc์€ ๋๋‚œ๋‹ค.

Scope

  1. global variables : available everywhere

  2. local variables : available certain methods

  3. class variables : members of a certain class

  4. instance variables : only available to particular instances of a class

Last updated