John
John

Reputation: 237

Finding string in array and using next

This specific exercise is a codewats Kata, which asks the user to search through an array, and if a String is found, to skip to the next item in the array. The array should then be printed without any of the strings included. [1, 2, "a", "b"] is the array being searching through. I expect [1, 2].

I tried:

def filter_list(l)
  print l
  i = 0
  while i < l.length
    l.each do|item| next if item.class == String
    return item
    i += 1
  end
end

I also tried this code without the while loop:

def filter_list(l)
  print l
  l.each do |item| next if item.class == String
    return item
  end
  print l
end

Both methods return the same result:

1

My code only returns the first element in the array.

Any guidance would be appreciated.

Upvotes: 0

Views: 51

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

Just out of curiosity:

arr = [1, 2, 2, "a", "b"]
(arr.map(&:to_s) - arr).map(&:to_i)
#⇒ [ 1, 2, 2 ]

 zeroes = arr.count(0)
 arr.map(&:to_i) - [0] + [0] * zeroes

Upvotes: 0

sawa
sawa

Reputation: 168269

[1, 2, "a", "b"].grep(Integer) # => [1, 2]
[1, 2, "a", "b"].grep_v(String) # => [1, 2]

Upvotes: 2

Ropeney
Ropeney

Reputation: 1065

If you're just looking to remove every String from an array you can use #reject.

array = [1,2,"a","b"]
=> [1, 2, "a", "b"]
array.reject { |element| element.is_a? String }
=> [1, 2]

Upvotes: 2

Related Questions