0
\$\begingroup\$

I would like to refactor this block, it looks clunky:

# refactor me
receive_payment_on = false
config[:sections].each do |section|
  if section[:applicants]
    section[:applicants][:sections].each do |app_sec|
      if app_sec[:employment] && app_sec[:employment][:receive_payment_on]
        receive_payment_on = true
      end
    end
  end
end
\$\endgroup\$

3 Answers 3

2
\$\begingroup\$

Put your code into a method. So you get rid of the temporary variable, its cleaner and you can leave your method with a return as soon as you find the first true. (A break to leave the loop will have the same effect.)

In addition to that I'm a big friend of guard conditions. Invert if section[:applicants] ... end to if !section[:applicants] next, so you have one nesting level less.

...
config[:sections].each do |section|
   if !section[:applicants] next
   section[:applicants][:sections].each do |app_sec|
       if app_sec[:employment] && app_sec[:employment][:receive_payment_on]
           return true
       end
   end
end
return false
\$\endgroup\$
2
  • \$\begingroup\$ thanks for the awnser but i ended up using \$\endgroup\$
    – Francois
    Commented Mar 19, 2013 at 7:46
  • \$\begingroup\$ receive_payment_on = true if config[:sections].join.include? 'next_paid_on' \$\endgroup\$
    – Francois
    Commented Mar 19, 2013 at 7:47
2
\$\begingroup\$

Don't use a for-loop (each), that's how you'd do it in language like C, in Ruby we have handy functional abstractions (or can build them if not present) like Enumerable#any?:

receive_payment_on = config[:sections].any? do |section|
  if section[:applicants]
    section[:applicants][:sections].any? do |app_sec|
      app_sec[:employment] && app_sec[:employment][:receive_payment_on]
    end
  end
end
\$\endgroup\$
1
\$\begingroup\$

how about using modifiers

receive_payment_on = config[:sections].any? do |section|
    section[:applicants][:sections].any? do |app_sec|
      app_sec[:employment] ? app_sec[:employment][:receive_payment_on] : false 
    end if section[:applicants]
end

(based on tokland's answer)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.