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

Array बनाना

एक array items की एक ordered list है जो साथ रखी गई है, numbers वाली lockers की एक row की तरह। आप square brackets से एक बना सकते हैं और इसे कुछ भी से भर सकते हैं।

In this page:

  1. Array Creation
Syntax
ruby
array = [value1, value2, value3]
array = Array.new(size, default_value)
array = %w[word1 word2 word3]

Array Creation

एक Ruby array square brackets से बनता है, [1, 2, 3], या Array.new से, और mixed types के elements hold कर सकता है क्योंकि Ruby dynamically typed है।

Arrays ordered और zero-indexed हैं। Array.new(n) { |i| ... } हर index के लिए एक block call करके एक array बनाता है, programmatically data generate करने के लिए useful।

Note: Array.new(5) { |i| i * i } एक separate loop के बिना एक line में [0, 1, 4, 9, 16] बनाता है।

उदाहरण: Array Creation

markup
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, true]
squares = Array.new(5) { |i| i * i }

puts fruits.inspect
puts mixed.inspect
puts squares.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. Array.new(3, []) इस्तेमाल करना, जहाँ सारे elements same array object हैं; Array.new(3) { [] } इस्तेमाल करें।
  2. length से आगे एक index इस्तेमाल करना जैसे fruits[10], जो एक error की बजाय nil return करता है।
  3. commas के साथ %w[a b c] लिखना, जो commas को strings के अंदर डाल देता है।
🔒

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.