2011-03-27 92 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}