开发者

Creating a reach definition

开发者 https://www.devze.com 2023-02-19 22:45 出处:网络
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 p

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}
0

精彩评论

暂无评论...
验证码 换一张
取 消