开发者

Inline array slicing

Hia! I was wondering about an interesting thing recently. Say I have this snippet:

params['path'].split('/').delete_at(-1).each do |dir|
   # some work

where

params['path'] = 'lorem/ipsum/dir/file.ext' #for instance

What I actually want to do is to iterat开发者_运维技巧e over all members of the ad hoc array except the last one. The snippet obviously doesn't work, because delete_at returns the deleted element.

Is there any way to slice array with "inline" syntax? Or am I terribly missing something? Do you know some other tricks to make similar method chaining easier?


Just use Array#[] with a range:

params['path'].split('/')[0..-2].each


Use the Array[range] syntax:

params['path'].split('/')[0...-1].each do |dir|
    # ...

0...-1 means from index 0 to index 1 from the end exclusive.

This is the same as .slice(0...-1).

See the docs here

Try it here: http://codepad.org/HyZ2GHxo


You may want to use File.dirname instead:

File.dirname(params['path']).split('/').each ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜