Alex Baranosky
Alex Baranosky

Reputation: 50094

How to tighten up this Ruby code?

How I can write this better. I was trying to use inject instead of each, but kept running into errors. I would like to tighten up the block.

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

Upvotes: 2

Views: 136

Answers (1)

rampion
rampion

Reputation: 89133

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.

Upvotes: 3

Related Questions