Skip to content

Instantly share code, notes, and snippets.

@travisdahlke
Forked from jphenow/conditional_array.rb
Last active December 21, 2015 03:19
Show Gist options
  • Save travisdahlke/6241008 to your computer and use it in GitHub Desktop.
Save travisdahlke/6241008 to your computer and use it in GitHub Desktop.
# 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
# Perly
def calculated_foo
((baz ? [baz.qux] : []) + [bar]).max
end
# ternary? ? && : ||
def calculated_foo
((baz && [baz.qux] || []) + [bar]).max
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment