Skip to content

Instantly share code, notes, and snippets.

@allard
Created February 9, 2022 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allard/23128821bf3bad10189dc65513ef5c6d to your computer and use it in GitHub Desktop.
Save allard/23128821bf3bad10189dc65513ef5c6d to your computer and use it in GitHub Desktop.
Ruby function to help pick the first available value.
# config/initializers/pick_first.rb in a rails app
class Object
# The pick_first function is a replacement for statements like users_value.present? ? users_value : default_value
# which using pick first can be replaced with pick_first users_value, default_value
# This is particularly helpful when you start getting into selecting the first out of three or more
# available values.
#
# pick_first "x", "y", "z" # => "x"
# pick_first nil, "y", "z" # => "y"
# pick_first "", "y", "z" # => "y"
# pick_first nil, "", "z" # => "z"
# pick_first nil, 1, 2 # => 1
# pick_first nil, nil # => nil
def pick_first(*input)
input.each do |value|
return value if value.to_s.present?
end
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment