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

push, pop, shift और unshift

push एक list के अंत में add करता है, pop अंत से remove करता है, shift front से remove करता है, और unshift front में add करता है। यह एक queue के दोनों ends पर लोगों के join या leave करने जैसा है।
Syntax
ruby
array.push(value)      # or array << value
array.pop
array.shift
array.unshift(value)

push, pop, shift, unshift

push (या <<) एक array के अंत में एक element add करता है, pop last element remove करके return करता है, shift पहला element remove करके return करता है, और unshift शुरुआत में एक element add करता है।

ये चारों methods आपको एक array को एक stack (push/pop) या एक queue (push/shift) की तरह इस्तेमाल करने देते हैं। इनमें से सब array को in place mutate करते हैं।

Note: << push के लिए एक common shorthand है, जैसे arr << 5, और Ruby में बहुत idiomatic है।

उदाहरण: push, pop, shift, unshift

markup
arr = [2, 3, 4]

arr.push(5)
arr << 6
arr.unshift(1)

puts arr.inspect

last = arr.pop
first = arr.shift

puts "Removed: #{first}, #{last}"
puts arr.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. यह उम्मीद करना कि pop और shift सिर्फ पढ़ते हैं, जब वे element remove और return करते हैं और array बदलते हैं।
  2. shift (front से remove करता है) और pop (end से remove करता है) mix up करना।
  3. arr.push([7, 8]) इस्तेमाल करना और दो नए items की उम्मीद करना, जब यह एक nested array add करता है; concat इस्तेमाल करें।
🔒

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.