Proc vs Lambda के अंतर
Procs और lambdas दिखने में same हैं लेकिन अलग तरीके से act करते हैं: एक lambda अपने inputs के बारे में strict है और सिर्फ खुद से return करता है, जबकि एक proc relaxed है। यह एक serious clerk बनाम एक laid-back helper जैसा है।
In this page:
Syntax
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
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?
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. #}
आम गलतियां
- यह उम्मीद करना कि एक Proc और एक lambda में
returnsame behave करेगा, जब एक lambda खुद से return करता है और एक Proc enclosing method से। - यह मान लेना कि एक Proc missing arguments के लिए एक error raise करता है, जब यह इन्हें
nilसे भरता है। - एक strict function के लिए एक Proc चुनना, जब एक lambda argument count check करता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: