开发者

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 regardin开发者_如何学Cg method chaining like this?

thanks, brandon


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]


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)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜