my reach definition is suppose to check an array to see if it can apply each to every member in the array, if not it is suppose to separate them out so each can be applied else it is suppose to just print out the array... this is really my first time using ruby so i need some help.. my code is this:
class String
remove_method(:each)
end
class Object
def reach
#checking if responds to each an开发者_高级运维d if so prints it out else
# returns the objects yielded
if(x.respond_to?(:each))
self.each {|x| print x, "\n"}
else
yield(self)
self.each {|x| print x, "\n"}
end
end
#test(remove before submitting)
[4, 13, 18, "fred", "alice"].each { |x| print x, "\n"}
[4, 13, 18, "fred", "alice"].reach {|x| print x, "\n"}
[4, [13, 88], [19, "fred", "snark"], "alice"].each { |x| print x, "\n"}
[4, [13, 88], [19, "fred", "snark"], "alice"].reach { |x| print x, "\n"}
gets #waits for user to hit enter to exit the program
I think that my else part is correct but that my if part is what i am struggling with... I wrote code to check to see if it responds to "each" and if it does then apply each to every element of the array.. else yield itself and then apply each to every element of the array...
If I understand you correctly, you want to recursively call each
(or reach
, anyway) on every element which supports it? Try something like:
module Enumerable
def reach &block
each do |e|
block.call(e)
if e.respond_to?(:each)
e.each(&block) # or, perhaps, e.reach?
end
end
end
end
Basically, your algorithm touches all elements in a nested array. For this, you can use then flatten
method.
arr = [4, [13, 88], [19, "fred", "snark"], "alice"]
arr.flatten.each {|it| puts it}
精彩评论