tags:

views:

69

answers:

3

beginning my foray into ruby, and literally the first thing I tried to do was:

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

which upon inspection returned

"" 

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

+2  A: 

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)
Mark Byers
+5  A: 

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]
slainer68
A: 

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"]
Mladen Jablanović
thanks for this example.
Orbit