Array बनाना
एक array items की एक ordered list है जो साथ रखी गई है, numbers वाली lockers की एक row की तरह। आप square brackets से एक बना सकते हैं और इसे कुछ भी से भर सकते हैं।
In this page:
Syntax
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
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
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. #}
आम गलतियां
Array.new(3, [])इस्तेमाल करना, जहाँ सारे elements same array object हैं;Array.new(3) { [] }इस्तेमाल करें।- length से आगे एक index इस्तेमाल करना जैसे
fruits[10], जो एक error की बजायnilreturn करता है। - commas के साथ
%w[a b c]लिखना, जो commas को strings के अंदर डाल देता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: