-1
   var.split('/').delete_at(0)

upon inspection returns

"" 

no matter what the string, however....

   var.split('/')
   var.delete_at(0)

gives me no trouble. this is probably a stupid question, but are there some sort of restrictions/limitations regarding method chaining like this?

thanks, brandon

1
  • 3
    Please provide the input and output. Commented Oct 31, 2010 at 1:19

3 Answers 3

8

The delete_at method deletes the element but returns the deleted element not the new array.

If you want to always return the object, you can use the tap method (available since Ruby 1.8.7).

a = [1, 2, 3, 4, 5, 6, 7]
a.delete_at(0) # => 1
a # => [2, 3, 4, 5, 6, 7]

a = [1, 2, 3, 4, 5, 6, 7]
a.tap { |a| a.delete_at(0) } # => returns [2, 3, 4, 5, 6, 7]
a # => [2, 3, 4, 5, 6, 7]
Sign up to request clarification or add additional context in comments.

Comments

2

literally the first thing I tried to do was:

var.split('/').delete_at(0)

which upon inspection returned

""

no matter what the string

Are you sure? Try the string 'a/b':

irb(main):001:0> var = 'a/b'
=> "a/b"
irb(main):003:0> var.split('/').delete_at(0)
=> "a"

Note that the return value is the element deleted, not the array. The array which you created by performing the split was not stored anywhere and now you have no reference to it. You probably want to do this instead:

a = var.split('/')
a.delete_at(0)

Comments

0

If you always need to delete the first element, you can use other methods that return the object itself, such as slice!, for example:

s = 'foo/bar/baz'
#=> "foo/bar/baz"
s.split('/').slice!(1..-1)
#=> ["bar", "baz"]

Comments

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.