Skip to content

Instantly share code, notes, and snippets.

@pbyrne
Last active December 21, 2015 03:18
Show Gist options
  • Save pbyrne/6240889 to your computer and use it in GitHub Desktop.
Save pbyrne/6240889 to your computer and use it in GitHub Desktop.
I'm building a small array dynamically and then picking the maximum value. I have problems with each formulation. Which choice is less evil?
# This option has the most clarity, but I generally hate local variables in a
# method, preferring to use tap.
def calculated_foo
available_foos = []
available_foos << bar
available_foos << baz.qux if baz
available_foos.max
end
# It's a little less clear, unless you know what tap is, and `end.max` is
# painful to look at.
def calculated_foo
[].tap do |available_foos|
available_foos << bar
available_foos << baz.qux if baz
end.max
end
# This avoids the painful `end.max` for a more-common `}.max`, but goes against
# the culture of using do/end for multi-line blocks.
def calculated_foo
[].tap { |available_foos|
available_foos << bar
available_foos << baz.qux if baz
}.max
end
@jonkarna
Copy link

[bar, baz ? baz.qux : nil].compact.max

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