Good day, I am developing a ruby method that tells me if a number is colorful, this time only with 3-digit numbers.
def colorful?(number)
# TODO: return true if the number is colorful, false otherwise
single_number = number.to_s.chars
array = []
for i in (0..single_number.size-1)
single_number.each_slice(i + 1) { |a| array << a }
end
array
end
p colorful?(263)
For now as I go along, this method returns me[["2"], ["6"], ["3"], ["2", "6"], ["3"], ["2", "6", "3"]]
I would like to know if there is any way to make each_slice(i) return an array of the size of the argument. For now, when it gets to each_slice(2) it returns a ["2", "6"], ["3"]
, I would like it to return ["2", "6"], ["6", "3"]
.
Is there any way to force each_slice to return only arrays of the size that I indicate?
Thanks in advance
Use Enumerable#each_cons instead of
each_slice
:As an improvement to your code, you could opt for
each
(or better yet,each_with_object
to avoid the variablearray
) instead of thefor
(for
rarely taken care of in Ruby):Another option (the best to my liking) can be with
flat_map
andmap
, which shows simplify the code more: