如何在迭代数组时使用 Array#delete?

发布于 2024-09-09 08:04:05 字数 232 浏览 3 评论 0原文

我有一个数组,我想迭代并删除一些元素。这不起作用:

a = [1, 2, 3, 4, 5]
a.each do |x|
  next if x < 3
  a.delete x
  # do something with x
end
a #=> [1, 2, 4]

我希望 a[1, 2]。我该如何解决这个问题?

I have an array that I want to iterate over and delete some of the elements. This doesn't work:

a = [1, 2, 3, 4, 5]
a.each do |x|
  next if x < 3
  a.delete x
  # do something with x
end
a #=> [1, 2, 4]

I want a to be [1, 2]. How can I get around this?

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

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

发布评论

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

评论(4

伴梦长久 2024-09-16 08:04:05

a.delete_if { |x| x >= 3 }

请参阅方法文档 这里

更新:

您可以在块中处理x:

a.delete_if do |element|
  if element >= 3
    do_something_with(element)
    true # Make sure the if statement returns true, so it gets marked for deletion
  end
end

a.delete_if { |x| x >= 3 }

See method documentation here

Update:

You can handle x in the block:

a.delete_if do |element|
  if element >= 3
    do_something_with(element)
    true # Make sure the if statement returns true, so it gets marked for deletion
  end
end
昵称有卵用 2024-09-16 08:04:05

您不必从数组中删除,您可以这样过滤它:

a = [1, 2, 3, 4, 5]

b = a.select {|x| x < 3}

puts b.inspect # => [1,2]

b.each {|i| puts i} # do something to each here

You don't have to delete from the array, you can filter it so:

a = [1, 2, 3, 4, 5]

b = a.select {|x| x < 3}

puts b.inspect # => [1,2]

b.each {|i| puts i} # do something to each here
爱冒险 2024-09-16 08:04:05

我不久前问过这个问题。

在 Ruby 中迭代时删除?

它不起作用,因为 Ruby 退出了 .each尝试删除某些内容时发生循环。如果您只是想从数组中删除内容,则 delete_if 可以工作,但如果您想要更多控制,我在该线程中提供的解决方案可以工作,尽管它有点丑陋。

I asked this question not long ago.

Deleting While Iterating in Ruby?

It's not working because Ruby exits the .each loop when attempting to delete something. If you simply want to delete things from the array, delete_if will work, but if you want more control, the solution I have in that thread works, though it's kind of ugly.

简美 2024-09-16 08:04:05

另一种方法是使用 reject!,这可以说更清晰,因为它有一个 ! ,这意味着“这将改变数组”。唯一的区别是,如果未进行任何更改,reject! 将返回 nil

a.delete_if {|x| x >= 3 }

或者

a.reject! {|x| x >= 3 }

两者都可以正常工作。

Another way to do it is using reject!, which is arguably clearer since it has a ! which means "this will change the array". The only difference is that reject! will return nil if no changes were made.

a.delete_if {|x| x >= 3 }

or

a.reject! {|x| x >= 3 }

will both work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文