Ruby assignment code altogther


def dostuff(&code) 
  code.call(7)
end

puts dostuff {|x| x + 9}

class NestedArray 
  include Enumerable # Enumerable is a module, not a class
                     # modules are included, not subclassed
  def initialize obj
    @narray = obj
  end 
end

na = NestedArray.new([[6,7],[8],[[9, 6]]])
p na
#p na.each {|z| puts (z + z)} # need to define each for this to work

class NestedArray 
  # defining each for nested arrays 
private
# a private recursive method, iterates over nested arrays
# with the code block in &code
# unfortunately, you can only pass one code parameter
 def _each (obj,&code)
    obj.each do |x| 
      if (x.instance_of? Array) 
        _each(x,&code)
      else 
        code.call(x)
      end
    end
 end
 public 
 # the public each method, calls the recursive one with the 
 # nested arrays storage as the parameter
 def each(&code)
   _each(@narray, &code)
 end    
end

na.each {|y| puts "Here is #{y}"}

#################### Optional material ##################################
###### may be used to write a traverse-like function in #################
###### Nested Array to write all other methods as calls to traverse #####
 
# creating a function that you can pass to another function
add_two = lambda {|x| x + 2}
p add_two.call(5)

repeat = lambda {|y, z| y.call(y.call(z))}

# functions can now be passed around 
# cannot do it with blocks :-(
def call_two_functions(f1, f2) 
 return f2.call(f1, 5)
end

p call_two_functions(add_two, repeat)

CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.