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
@nusco
Copy link

nusco commented Aug 15, 2013

[bar, baz ? baz.qux : 0].max

Because my code is for the right ppl only, knowhadimean?

Oh, and I fail in the presence of negative numbers because I'm too cool to care.

But if you're one of those guys who actually want their code to be readable, then may I suggest something completely different:

def good_method_name_that_exposes_intent
  return bar unless baz
  [bar, baz.qux].max
end

@kevinmarx
Copy link

function calculatedFoo() {
  return Math.max.apply(Math, [bar, baz ? baz.qux : 0])
}

:trollface:

@stuartnelson3
Copy link

module NullObj
  def self.qux;0;end
end

[bar, (baz || NullObj).qux].max

i personally would just pick one of your options and go (problem the first one with the local), but i figured i'd add something to the discussion.

@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