繁体   English   中英

Ruby的`delete_if`方法

[英]Ruby's `delete_if` method

这段代码:

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的索引来迭代,并在针对元素计算块之后立即删除元素。 它如下进行。

  • 索引x0

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM