0

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.

2
  • Once again: you want to filter out all the strings from the array? Commented Jun 25, 2016 at 16:44
  • Yes exactly. And return the array with only the integers. Commented Jun 25, 2016 at 17:11

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.