Created
December 19, 2009 21:44
-
-
Save softcraft-development/260253 to your computer and use it in GitHub Desktop.
Concatenate two strings if not nil
This file contains 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
class String | |
def &(value = nil, default = "") | |
value ? self + value.to_s : default.to_s | |
end | |
end | |
# Mostly for consistency; not terribly useful | |
class NilClass | |
def &(value = nil, default = "") | |
default.to_s | |
end | |
end | |
# Usage Examples | |
"word" & " with suffix" # "word with suffix" | |
"word" & nil # "" | |
"word".&(nil,"nothing") # "nothing" | |
# The intent behind this was for generating ImageMagick geometry strings | |
# See http://www.imagemagick.org/script/command-line-processing.php#geometry | |
# Assume a hash of arguments called @args: | |
width = args[:width] # optional | |
height = args[:height] # optional | |
geo = ("" & width) + ("x" & height) | |
# width = nil, height = nil, geo = "" | |
# width = 100, height = nil, geo = "100" | |
# width = nil, height = 100, geo = "x100" | |
# width = nil, height = 100, geo = "100x100" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment