Skip to content

Instantly share code, notes, and snippets.

@softcraft-development
Created December 19, 2009 21:44
Show Gist options
  • Save softcraft-development/260253 to your computer and use it in GitHub Desktop.
Save softcraft-development/260253 to your computer and use it in GitHub Desktop.
Concatenate two strings if not nil
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