← Back to Ruby Course | Chapter 4: Arrays | Lesson 7 of 7

Ranges क्या हैं

एक range values के एक run के लिए एक shortcut है, जैसे एक से पाँच तक इन्हें सब लिखे बिना। दो dots last number include करते हैं और तीन dots इसे छोड़ देते हैं।

In this page:

  1. Ranges
Syntax
ruby
inclusive = (start..finish)
exclusive = (start...finish)
range.to_a
range.include?(value)

Ranges

एक range, 1..5 (inclusive) या 1...5 (end exclusive) की तरह लिखी जाती है, values की एक sequence represent करती है और .to_a से एक array में convert हो सकती है।

Ranges आमतौर पर iteration ((1..5).each) के लिए और arrays या strings slice करने के लिए इस्तेमाल होती हैं। ये lazily evaluate होती हैं, इसलिए (1..Float::INFINITY) तुरंत एक infinite array बनाने की कोशिश नहीं करता।

Warning: 1...5 (तीन dots) final value exclude करता है, जबकि 1..5 (दो dots) इसे include करता है -- एक नज़र में confuse करना आसान है।

उदाहरण: Ranges

markup
inclusive = (1..5).to_a
exclusive = (1...5).to_a

puts inclusive.inspect
puts exclusive.inspect

(1..3).each { |n| puts "Number: #{n}" }
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. 1..5 इस्तेमाल करना और last number के exclude होने की उम्मीद करना, जब .. इसे include करता है और ... exclude करता है।
  2. (5..1).to_a call करना और [5, 4, 3, 2, 1] की उम्मीद करना, जब एक backward range empty होती है; 5.downto(1) इस्तेमाल करें।
  3. बिना parentheses के 1..5.each लिखना, जो 5 पर each call करता है; (1..5).each लिखें।
चैप्टर सारांश
  • Arrays push, pop, shift, और unshift जैसे methods से बनते और बदलते हैं।
  • each, map, select, और reject elements पर iterate और transform करते हैं।
  • flatten, zip, दूसरे array methods, और ranges collections के साथ काम करने में मदद करते हैं।
🔒

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.