← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 4 of 6

Enumerable क्या है

Enumerable एक class को list tools का एक पूरा set देता है जैसे map और select, जब तक यह जानती हो अपने items से एक-एक करके कैसे गुज़रना है। यह किसी भी चीज़ को जिसे walk through किया जा सके helpers की एक kit देने जैसा है।

In this page:

  1. Enumerable
Syntax
ruby
class ClassName
  include Enumerable

  def each
    # yield each element
  end
end

Enumerable

Enumerable mix करना एक class को .map, .select, .sort, .include?, और दर्जनों और methods देता है, जब तक class एक single each method define करे जो describe करे कि यह अपने elements पर iterate कैसे करती है।

यही exactly वह तरीका है जिससे Array और Hash को इतने shared collection methods मिलते हैं। यह Ruby के "एक method provide करो, कई free में पाओ" module design का एक powerful example है।

Note: सिर्फ each implement करना और Enumerable include करना automatically दर्जनों collection methods unlock करता है -- mixin power का Ruby के सबसे अच्छे examples में से एक।

उदाहरण: Enumerable

markup
class Playlist
  include Enumerable

  def initialize(songs)
    @songs = songs
  end

  def each
    @songs.each { |song| yield song }
  end
end

playlist = Playlist.new(["Song A", "Song B", "Song C"])

puts playlist.map { |s| s.upcase }.inspect
puts playlist.include?("Song B")
puts playlist.sort.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. each define किए बिना Enumerable include करना, इसलिए कोई भी method काम नहीं करता।
  2. each में yield की बजाय return values इस्तेमाल करना, इसलिए map और select को कुछ नहीं मिलता।
  3. यह उम्मीद करना कि Enumerable methods arrays जैसे काम करेंगे, जैसे playlist[0], जब यह सिर्फ iteration methods देता है।
🔒

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.