2

I want to remove the first digit of my array and return the array without the first term

new_array always comes out as just a single number

n is an integer

array = (n.to_s).split(//)

print array

new_array = array.delete_at(0)

puts new_array
3
  • 1
    Your question sounds a bit ambiguous. Do you want to delete the 1st element from array (i.e. altering array) or do you just want a new array without the 1st element? (i.e. without altering array) Commented Jul 11, 2019 at 11:02
  • BTW, your code (n.to_s).split(//) returns an array of characters, not an array of digits. Commented Jul 11, 2019 at 11:05
  • Write a new method which runs the last two lines of code you have written. Commented Jul 11, 2019 at 11:19

5 Answers 5

2

Drops first n elements from Array and returns the rest of the elements in an array.

 a = [41,42,43,45,46]
 => [41, 42, 43, 45, 46] 
 a.drop 1
 => [42, 43, 45, 46]
Sign up to request clarification or add additional context in comments.

1 Comment

drop doesn't delete elements from the existing array, it returns a new array without those elements.
0

You could use Integer#digits and Object#tap this way:

n = 12345678
position = 3
n.digits.reverse.tap { |ary| ary.delete_at(position) }

#=> [1, 2, 3, 5, 6, 7, 8]

position = 0 remove the firs digit.

Comments

0
irb(main):001:0> arr = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):002:0> arr.shift
=> 1
irb(main):003:0> arr
=> [2, 3, 4, 5, 6, 7, 8, 9, 10]

I hope that helpful

Comments

0

You can use array method drop to delete n number of elements from array

arr = [1, 2, 3, 4, 5]
arr.drop 2
=> [3, 4, 5]

ref: https://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-drop

2 Comments

drop doesn't delete elements from the existing array, it returns a new array without those elements.
True, the requirement is to return a new array without first element. hope it would serve the purpose
-1

Because delete_at returns the deleted item. If you want to remove and retrieve at the same time for the first item, you can use -

new_array = array.drop(1)

3 Comments

how do i do the same thing but with any position in the array
There is no predefined method for this in ruby. BTW delete_at method already deleted the item from the original array, so you can use it. Or you can assign it to a new variable in the next line.
Yes, you are right, I have not checked it, I have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.