Enumerable क्या है
Enumerable एक class को list tools का एक पूरा set देता है जैसे map और select, जब तक यह जानती हो अपने items से एक-एक करके कैसे गुज़रना है। यह किसी भी चीज़ को जिसे walk through किया जा सके helpers की एक kit देने जैसा है।
In this page:
Syntax
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
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
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. #}
आम गलतियां
eachdefine किए बिनाEnumerableinclude करना, इसलिए कोई भी method काम नहीं करता।eachमेंyieldकी बजायreturnvalues इस्तेमाल करना, इसलिएmapऔरselectको कुछ नहीं मिलता।- यह उम्मीद करना कि Enumerable methods arrays जैसे काम करेंगे, जैसे
playlist[0], जब यह सिर्फ iteration methods देता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: