Proc&Lamda
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
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 { |param| block }
lambda { puts "Hello!" } == Proc.new { puts "Hello!" }
argument ๊ฐ ์ค๋ฅ๊ฐ ๋ฌ์๋ proc์ ๋ฌด์ํ๊ณ nil์ฒ๋ฆฌ ํ ๋์ด๊ฐ๋๋ฐ lambda๋ ์ค๋ฅ๊ฐ๋๋ค.
lambda๋ call์ด ๋๋ฉด ๋ค์ ๋ง์ง๋ง ์ฝ๋๋ก ๋์๊ฐ๋๋ฐ proc์ ๋๋๋ค.
global variables : available everywhere
local variables : available certain methods
class variables : members of a certain class
instance variables : only available to particular instances of a class