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
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
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
Uri Agassi
return is no good here (LocalJumpError: unexpected return)Denis de Bernardy
@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.)Uri Agassi
You say in your explanation "... and
return or break" - return won't work...Denis de Bernardy
@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; fooUri Agassi
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.