Brandon Frohbieter
Brandon Frohbieter

Reputation: 18139

ruby method chaining

   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

Upvotes: -1

Views: 1242

Answers (3)

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

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"]

Upvotes: 0

Nicolas Blanco
Nicolas Blanco

Reputation: 11299

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]

Upvotes: 8

Mark Byers
Mark Byers

Reputation: 838216

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)

Upvotes: 2

Related Questions