Method Objects क्या हैं
एक method object एक existing method को ऐसी चीज़ में बदल देता है जिसे आप carry around और बाद में call कर सकते हैं, एक friend का number अपने phone में save करने की तरह। आप फिर इसे दूसरे code को pass कर सकते हैं।
In this page:
Syntax
method_object = method(:method_name)
method_object.call(argument)
collection.map(&method(:method_name))
Method Objects
method(:name) एक existing method को एक callable Method object में convert करता है, जो काफी हद तक एक lambda जैसा behave करता है और store, pass around, या .to_proc से convert हो सकता है।
यह आपको एक named method को एक first-class value की तरह treat करने देता है, exactly जैसे आप एक lambda के साथ करते। यह खासकर map जैसी किसी चीज़ को एक block में wrap किए बिना एक existing method directly pass करने के लिए handy है।
Note:
numbers.map(&method(:square)) map में सीधे एक existing method pass करता है, एक redundant wrapper block से बचते हुए।उदाहरण: Method Objects
def square(x)
x * x
end
square_method = method(:square)
puts square_method.call(5)
numbers = [1, 2, 3, 4]
puts numbers.map(&method(:square)).inspect
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. #}
आम गलतियां
- बिना colon के
method(square)लिखना, जो Method object पाने की बजाय तुरंतsquarecall करता है;method(:square)इस्तेमाल करें। - बिना
&के&method(:square)इस्तेमाल करना, इसलिएmapको Method एक argument की तरह मिलता है, block नहीं। - यह उम्मीद करना कि method redefine होने पर Method object बदल जाएगा।
चैप्टर सारांश
- Blocks और
yieldmethods को code pass करते हैं। - Procs और lambdas objects में code store करते हैं, और ये arguments और returns handle करने में अलग हैं।
- Method objects आपको methods को values की तरह treat करने देते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: