← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 5 of 6

Proc vs Lambda के अंतर

Procs और lambdas दिखने में same हैं लेकिन अलग तरीके से act करते हैं: एक lambda अपने inputs के बारे में strict है और सिर्फ खुद से return करता है, जबकि एक proc relaxed है। यह एक serious clerk बनाम एक laid-back helper जैसा है।
Syntax
ruby
my_proc = Proc.new { |a, b| expression }    # lenient arguments
my_lambda = ->(a, b) { expression }         # strict arguments
# return exits the method in a proc, only the lambda in a lambda

Proc बनाम Lambda Differences

दो key differences हैं argument strictness (एक lambda गलत argument count पर ArgumentError raise करता है, एक Proc नहीं) और return behavior (एक lambda का return सिर्फ lambda से exit करता है, जबकि एक Proc का return पूरी तरह enclosing method से exit करता है, जो surprising control flow cause कर सकता है)।

इसकी वजह से, lambdas आमतौर पर safer default choice हैं। एक Proc object पर .lambda? आपको बताता है यह actually कौन-सा kind है।

Warning: एक Proc (lambda नहीं) के अंदर एक return पूरी तरह enclosing method से exit करता है -- यह confusing bugs का एक common source है।

उदाहरण: Proc vs Lambda Differences

markup
strict_lambda = lambda { |x, y| x + y }
lenient_proc = Proc.new { |x, y| (x || 0) + (y || 0) }

begin
  strict_lambda.call(1)
rescue ArgumentError => e
  puts "Lambda raised: #{e.class}"
end

puts lenient_proc.call(1)  # no error, y is nil -> treated as 0

puts strict_lambda.lambda?
puts lenient_proc.lambda?
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. #}
आम गलतियां
  1. यह उम्मीद करना कि एक Proc और एक lambda में return same behave करेगा, जब एक lambda खुद से return करता है और एक Proc enclosing method से।
  2. यह मान लेना कि एक Proc missing arguments के लिए एक error raise करता है, जब यह इन्हें nil से भरता है।
  3. एक strict function के लिए एक Proc चुनना, जब एक lambda argument count check करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.