Skip to content

Instantly share code, notes, and snippets.

@NIA
Last active December 11, 2015 11:48
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 NIA/4596482 to your computer and use it in GitHub Desktop.
Save NIA/4596482 to your computer and use it in GitHub Desktop.
Illustration of using tail conditions for http://stackoverflow.com/a/14460975/693538 SO answer
# Check if it is present...
if row[1].present?
# If it is present:
# Check if it is a subclass of numeric...
if row[1].is_a? Numeric
# If it is present AND it is a number:
oem = row[1].to_i.to_s # <- Convert it to string
else
# If it is present BUT is not a number:
oem = row[1] # ...then it is string, conversion not required
end
else
# If it is NOT present:
oem = nil
end
# OR (shorter) -- using such feature of Ruby that every statement returns its value, even 'if' does it (returns last statement of executed branch)
oem = if row[1].present?
if row[1].is_a? Numeric
row[1].to_i.to_s
else
row[1]
end
end
# OR (even shorter)
oem = if row[1].present?
row[1].is_a?(Numeric) ? row[1].to_i.to_s : row[1]
end
# FINALLY (one-liner) -- the BEST one
oem = row[1].is_a?(Numeric) ? row[1].to_i.to_s : row[1] if row[1].present?
# OR EVEN (with ?: operators) -- the WORST one
oem = row[1].present? ? ( row[1].is_a?(Numeric) ? row[1].to_i.to_s : row[1] ) : nil # OH SHI-- how many '?' signs!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment