Proc.new
A Proc wraps a block into a real object you can save in a variable and run whenever you want. It is like recording instructions on a card you can keep and reuse.
In this page:
Syntax
proc_name = Proc.new { |param| expression }
proc_name.call(argument)
Proc.new
A Proc wraps a block of code as a reusable, storable object that can be assigned to a variable and called later with .call.
Proc.new { ... } (or the shorthand proc { ... }) creates one explicitly, unlike a plain block which only exists inline at a single call site. Procs are lenient about argument count -- passing too many or too few doesn't raise an error.
Note:
A Proc silently ignores extra arguments and fills missing ones with nil, unlike a Lambda which enforces arity strictly.
Example: Proc.new
square = Proc.new { |x| x * x }
puts square.call(5)
puts square.(6)
puts square[7]
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling a Proc with the wrong number of arguments and expecting an error, when extra arguments are ignored and missing ones become
nil. - Using
returninside a Proc, which returns from the enclosing method and can raiseLocalJumpErrorat top level. - Forgetting
.call,.()or[], so the Proc is never run.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: