R. Lee
R. Lee

Reputation: 11

Ruby's `delete_if` method

This code:

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

returns ["b","a","c","d"] instead of ["b","c","d","b"]. Why doesn't this delete if x=="a"? Can anyone tell me why this method doesn't work as I hope?

Upvotes: 1

Views: 1742

Answers (1)

sawa
sawa

Reputation: 168269

delete_if iterates by incrementing the index for x, and deletes an element immediately after evaluating the block with respect to the element. It proceeds like the following.

  • index of 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"]
    
  • index of x: 1

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

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

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

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

Upvotes: 3

Related Questions