views:

98

answers:

1

I'm wondering how I can write this better. I was trying to use inject instead of each, but kept running into errors. Mostly I'd like to tighten up the block. Any thoughts?

def to_proc
    levels_of_nesting = @fields.zip(@orderings)

    procedure = nil
    levels_of_nesting.each do |field, ordering|
      procedure = proc_for(field, ordering) and next if procedure.nil?
      procedure = procedure.decorate_w_secondary_sorting_level(proc_for(field, ordering))
    end
    procedure
  end
+3  A: 

I'd use a map to run everything through proc_for, and then combine the procs using inject.

def to_proc
  @fields.zip(@orderings).map do |field, ordering|
    proc_for(field, ordering)
  end.inject do |prev,curr|
    prev.decorate_w_secondary_sorting_level curr
  end
end

This makes the iterator methods do the flow control for you, avoiding spurious nils and if statements.

rampion
Ahhh very nice. Thx.
Alex Baranosky