← Back to Ruby Course | Chapter 5: Hashes | Lesson 5 of 7

Hashes पर select और reject

Hashes पर select और reject इनकी pairs को एक rule से filter करते हैं, सिर्फ वे contacts चुनने की तरह जो पास रहते हैं। select matches रखता है और reject इन्हें हटाता है।
Syntax
ruby
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

markup
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
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. यह उम्मीद करना कि एक hash पर select एक array return करेगा, जब यह एक hash return करता है।
  2. एक parameter वाला एक block इस्तेमाल करना जैसे { |pair| pair >= 70 }, score की बजाय एक array compare करते हुए।
  3. यह उम्मीद करना कि select hash बदल देगा, जब यह एक नया return करता है जब तक आप select! इस्तेमाल न करें।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.