Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Which is best, iteration or recursion?
# I originally refactored this method to a recursive solution, but I wonder whether
# that's really necessary. Is the alternative approach using inject easier to
# understand?
# Original method, with external iterator:
# Build breadcrumb list from an array of nested model instances, starting with the parent
# and ending with the lowest level child. Each breadcrumb needs to be created using a
# sub-array containing itself and its parents.
def build_breadcrumb_list model_hierarchy
output = []
while model_hierarchy.any? do
output << create_breadcrumb(model_hierarchy)
model_hierarchy.delete_at(-1)
end
output << root_breadcrumb
output.reverse.to_s.html_safe
end
# Refactored recursive version:
def build_breadcrumb_list model_hierarchy
if model_hierarchy.empty?
root_breadcrumb
else
build_breadcrumb_list(model_hierarchy[0..-2]) + create_breadcrumb(model_hierarchy)
end
end
# Refactored again to use inject instead:
def build_breadcrumb_list model_hierarchy
(1..model_hierarchy.length).inject(root_breadcrumb) do |out, n|
out << create_breadcrumb(model_hierarchy[0, n])
end
end
# So, which do you prefer? Is there a better way than either?
@MrJaba
Copy link

MrJaba commented Nov 11, 2010

Loading

@MrJaba
Copy link

MrJaba commented Nov 11, 2010

Personally I think I prefer the inject version; I find that a little more readable.

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment