Skip to content

Instantly share code, notes, and snippets.

@sparksp
Created February 23, 2016 15:59
Show Gist options
  • Save sparksp/a0522217f4bea189939d to your computer and use it in GitHub Desktop.
Save sparksp/a0522217f4bea189939d to your computer and use it in GitHub Desktop.
Try to cast to an integer
def try_to_i(string)
if string.to_i.to_s == string
string.to_i
else
string
end
end
@c0nspiracy
Copy link

def try_to_i(string)
  Integer(string)
rescue ArgumentError
  string
end

would help to know a little more about the context this is being used in.

@c0nspiracy
Copy link

Since we're only concerned with positive integers:

def column_letter_or_index(string)
  /\A\d+\z/ === string ? string.to_i : string
end

You'd probably want to .strip the string first to prevent accidental whitespace creeping in from the command-line.

@sparksp
Copy link
Author

sparksp commented Feb 24, 2016

@c0nspiracy I think you have to try really hard for white space to creep in from the command-line... e.g., by quoting your input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment