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

Method Objects क्या हैं

एक method object एक existing method को ऐसी चीज़ में बदल देता है जिसे आप carry around और बाद में call कर सकते हैं, एक friend का number अपने phone में save करने की तरह। आप फिर इसे दूसरे code को pass कर सकते हैं।

In this page:

  1. Method Objects
Syntax
ruby
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

markup
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
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. बिना colon के method(square) लिखना, जो Method object पाने की बजाय तुरंत square call करता है; method(:square) इस्तेमाल करें।
  2. बिना & के &method(:square) इस्तेमाल करना, इसलिए map को Method एक argument की तरह मिलता है, block नहीं।
  3. यह उम्मीद करना कि method redefine होने पर Method object बदल जाएगा।
चैप्टर सारांश
  • Blocks और yield methods को 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:

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.