2011-03-27 91 views
0

我的覆盖范围定义是假设检查数组以查看它是否可以将每个数组应用于数组中的每个成员,如果不是,则假设将它们分开,以便每个成员都可以应用,打印出来的阵列...这是真的使用Ruby,所以我需要一些帮助,我第一次..我的代码是这样的:创建覆盖范围定义

class String 
remove_method(:each) 
end 

class Object 
def reach 
    #checking if responds to each and 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 

我认为我的其他部分是正确的,但我如果一部分是我我正在努力......我写了代码来检查它是否响应“每个”,如果它确实对数组中的每个元素都应用了每个元素,则会自行产生,然后将每个元素应用到数组中的每个元素。 。

回答

1

如果我的理解正确无误,您想在每个支持它的元素上递归地调用each(或者reach,无论如何)?尝试类似:

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 
0

基本上,您的算法触及嵌套数组中的所有元素。为此,您可以使用flatten方法。

arr = [4, [13, 88], [19, "fred", "snark"], "alice"] 
arr.flatten.each {|it| puts it}