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 ...
精彩评论