Hashes पर select और reject
Hashes पर select और reject इनकी pairs को एक rule से filter करते हैं, सिर्फ वे contacts चुनने की तरह जो पास रहते हैं। select matches रखता है और reject इन्हें हटाता है।
In this page:
Syntax
filtered = hash.select { |key, value| condition }
filtered = hash.reject { |key, value| condition }
Hashes पर select और reject
hash.select { |k, v| ... } सिर्फ वे pairs रखने वाला एक नया hash return करता है जिनके लिए block true हो, और reject वे pairs return करता है जिनके लिए यह false हो -- arrays पर same filtering idea, key-value pairs पर apply।
जब एक hash पर call हों दोनों एक Hash return करते हैं, array नहीं। यह इसकी keys या values के आधार पर एक hash filter करने का idiomatic तरीका है।
Note:
एक Hash पर select/reject एक Hash वापस return करते हैं, map के उलट जो एक Array return करता है -- याद रखने लायक एक useful distinction।
उदाहरण: select and reject on Hashes
scores = { alice: 95, bob: 60, cara: 80 }
passing = scores.select { |name, score| score >= 70 }
failing = scores.reject { |name, score| score >= 70 }
puts passing.inspect
puts failing.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. #}
आम गलतियां
- यह उम्मीद करना कि एक hash पर
selectएक array return करेगा, जब यह एक hash return करता है। - एक parameter वाला एक block इस्तेमाल करना जैसे
{ |pair| pair >= 70 }, score की बजाय एक array compare करते हुए। - यह उम्मीद करना कि
selecthash बदल देगा, जब यह एक नया return करता है जब तक आपselect!इस्तेमाल न करें।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: