Ruby';s`delete_if`方法
此代码:Ruby';s`delete_if`方法,ruby,Ruby,此代码: 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\u如果通过增加x的索引进行迭代,并在对元素评估块后立即删除元素。它如下进行 x的索引:0 string
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\u如果
通过增加x
的索引进行迭代,并在对元素评估块后立即删除元素。它如下进行
: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"]
字符串
为空数组。您正在为数组中的每个项删除数组的第一个元素。由于上一个项目被删除后,下一个项目成为第一个元素,因此块始终返回true,从而导致空数组。一旦“a”被删除,“b”成为字符串[0],迭代器将移动到位置2,将新字符串[1]与字符串[0]进行比较,即“a”=“b”。与字符串[0]匹配的下一个可能的字符是最后一个“b”。为避免此问题,应使用不会更改原始字符串的:new_string=string.reject{char | char==string[0]}
。如果您仍然想使用,它总是修改原始字符串,那么您可以编写first_char=string[0]
,然后将{x | x==first_char}
放在delete_If
块中。在第一条语句之后,变量string
保存一个数组。你应该避免这种混乱的命名。同样,不要将变量array
用于哈希,也不要将变量hash
用于字符串。