内联数组切片

发布于 2024-12-05 12:14:48 字数 368 浏览 6 评论 0原文

嗨!最近我在想一件有趣的事情。假设我有这个片段:

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

其中

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

我真正想做的是迭代临时数组中除最后一个成员之外的所有成员。该代码段显然不起作用,因为 delete_at 返回已删除的元素。

有没有办法用“内联”语法来切片数组?或者我真的错过了什么?您是否知道一些其他技巧可以使类似的方法链接更容易?

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 iterate 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

征﹌骨岁月お 2024-12-12 12:14:48

只需使用 Array#[] 和一个范围:

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

Just use Array#[] with a range:

params['path'].split('/')[0..-2].each
め七分饶幸 2024-12-12 12:14:48

使用 Array[range] 语法:

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

0...-1 表示从索引 0 到索引 1结局独家。

这与 .slice(0...-1) 相同。

请参阅此处的文档

尝试一下这里: http://codepad.org/HyZ2GHxo


您可能想使用 File.dirname 代替:

File.dirname(params['path']).split('/').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 ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文