Created
February 9, 2022 01:16
-
-
Save allard/23128821bf3bad10189dc65513ef5c6d to your computer and use it in GitHub Desktop.
Ruby function to help pick the first available value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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