gpt4 book ai didi

Ruby 的 `delete_if` 方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:31 26 4
gpt4 key购买 nike

这段代码:

string="abacdb"
string=string.split("")
string.delete_if{|x| x==string[0]}
puts(string)

返回 ["b","a","c","d"] 而不是 ["b","c","d","b"] 。如果 x=="a" 为什么不删除?谁能告诉我为什么这个方法不能像我希望的那样工作?

最佳答案

delete_if 通过递增 x 的索引进行迭代,并在针对元素评估 block 后立即删除该元素。它像下面这样进行。

  • x 的索引:0

    string                      # => ["a", "b", "a", "c", "d", "b"]
    string[0] # => "a"
    x # => "a"
    delete_if{|x| x==string[0]} # => ["b", "a", "c", "d", "b"]
  • x 的索引:1

    string                      # => ["b", "a", "c", "d", "b"]
    string[0] # => "b"
    x # => "a"
    delete_if{|x| x==string[0]} # => ["b", "a", "c", "d", "b"]
  • x 的索引:2

    string                      # => ["b", "a", "c", "d", "b"]
    string[0] # => "b"
    x # => "c"
    delete_if{|x| x==string[0]} # => ["b", "a", "c", "d", "b"]
  • x 的索引:3

    string                      # => ["b", "a", "c", "d", "b"]
    string[0] # => "b"
    x # => "d"
    delete_if{|x| x==string[0]} # => ["b", "a", "c", "d", "b"]
  • x 的索引:4

    string                      # => ["b", "a", "c", "d", "b"]
    string[0] # => "b"
    x # => "b"
    delete_if{|x| x==string[0]} # => ["b", "a", "c", "d"]

关于Ruby 的 `delete_if` 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com