How to recreate the any? method in Ruby
Clash Royale CLAN TAG#URR8PPP
How to recreate the any? method in Ruby
I am trying to recreate the enumerable module in Ruby. I am up to the any? method and having difficulty returning true or false. Instead each array item is returned 1 by 1.. Here is my code:
def my_any?
return self.to enum unless block_given?
self.each do |i|
return true if i == yield(i)
end
end
nums = [3,5,7,3,6,10,20,16]
puts nums.my_any?x==6
Any ideas where I am going wrong?
2 Answers
2
You have two issues:
return false
each
return true if cond
any?
i == yield(i)
yield(i)
(The to enum
bit sounds off too, but that's unrelated to your question.)
to enum
Slotting those changes into your code:
def my_any?
# FIXME: return self.to enum unless block_given?
self.each do |i|
return true if yield i
end
false
end
self
@Stefan there is always a need in
self
in our humble lives :)– mudasobwa
Aug 10 at 18:54
self
You have three issues with your code: you should return an enumerator for this method when called without block, you should check just what yield
returns, and you should explicitly return false
on fail:
yield
false
def my_any?
return to_enum(:my_any?) unless block_given?
each return true if yield(i)
false
end
nums = [3,5,7,3,6,10,20,16]
puts nums.my_any?
#⇒ true
lazy = nums.my_any?
lazy.each
#⇒ true
Or, I would better use break
:
break
def my_any?
return to_enum(:my_any?) unless block_given?
each i == true
end
I cannot count the times when an asker wanted to recreate an
Enumerable
method and answers neglected to deal with the case where the method has no block and an enumerator is returned. Good to see you dealt with that very important aspect of the question.– Cary Swoveland
Aug 10 at 18:05
Enumerable
Whoops! Enumerable#any? only returns
true
or false
, never an enumerator. Strange. I'd think one may wish to write, for example, nums.any?.with_index x <= 6 && i >2
.– Cary Swoveland
Aug 10 at 18:13
true
false
nums.any?.with_index x <= 6 && i >2
@CarySwoveland
Enumerable#any?
is relatively young, nowadays people any not that picky :)– mudasobwa
Aug 10 at 18:49
Enumerable#any?
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There's no need for
self
– Stefan
Aug 10 at 13:24