1

I have an array filled with 0's, 1's, 3's and 4's and want to check inside the array, so that once a certain amount of the 4's have been found, a statement turns false.

5 Answers 5

3

Use the count method.

alist.count(4) >= n
# => true or false

n would be the certain number you want to check for.

Sign up to request clarification or add additional context in comments.

Comments

0

The documentation is the best place to start answering questions like this, ruby has a very rich set of functions on Array and Enumerable

def enough_4s?(array, how_many)
  array.count(4) >= how_many 
end

array = [1,1,1,2,3,4,4,4]
enough_4s?(array, 3)
#=> true
enough_4s?(array, 4)
#=> false

2 Comments

since .count(4) > x is shorter I don't see the need for an extra function
because it documents intention
0

[0,1,3,4,3].­count(4) > 2 => false

(e.g 2 is the expected count)

Comments

0

If the goal is to immediately stop searching upon locating enough 4s, use each or find or equivalent, and return or break, rather than count. For instance:

n = 2
([0,1,3,4]*5).find do |i|
  n -= 1 if i == 4
  break false if n == 0
end
# false

5 Comments

return is no good here (LocalJumpError: unexpected return)
@UriAgassi: The example I wrote is not using return. It's using break. One with each could do the same. One with map would be similar too (don't forget to return i in that case, else you'll get an array of nil.)
You say in your explanation "... and return or break" - return won't work...
@UriAgassi: well, yeah, it won't work outside of a function. But I would assume OP isn't using IRB. def foo; n = 2; ([0,1,3,4]*5).each { |i| n -= 1 if i == 4; return false if n == 0 }; end; foo
You did not enclose it in a functions, so not using IRB may cause more confusion, as the whole function this snippet will appear in will return unexpectedly.
0

Another solution, which stops as soon as it can is based on using any?:

def has_at_least?(arr, val, min)
  arr.any? do |i|
    i == val && (min -= 1).zero?
  end
end

has_at_least?([0,1,3,4]*5, 4, 2)
# => true

has_at_least?([0,1,3,4]*5, 4, 7)
# => false

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.