How to get strptime to raise ArgumentError with garbage trailing characters - ruby

We have to handle user specified date formats in our application. We decided to go with Date.strptime for parsing and validation, which works great, except for how it just ignores any garbage data entered. Here is an irb session demonstrating the issue
ree-1.8.7-2010.01 > require 'date'
=> true
ree-1.8.7-2010.01 > d = Date.strptime '2001-01-01failfailfail', '%Y-%m-%d'
=> #<Date: 4903821/2,0,2299161>
ree-1.8.7-2010.01 > d.to_s
=> "2001-01-01"
what we would like, is behavior more like this
ree-1.8.7-2010.01 > d = Date.strptime '2001failfailfail-01-01', '%Y-%m-%d'
ArgumentError: invalid date
Any suggestions would be appreciated

One possibility is to pass the resulting date through strftime using the same format and compare to the original string.
i.e. valid = Date.strptime(date_string, format).strftime(format) == date_string
One limitation of this is that it wouldn't handle leading 0s in parts of the date e.g. if you wanted to accept 2010-6-1 but strftime returned 2010-06-01 you wouldn't have a match.
Also, I'm not sure if this is what you meant or not, but your second example Date.strptime '2001failfailfail-01-01', '%Y-%m-%d' does raise an ArgumentError. It seems like only trailing junk is ignored.

one way is to define a new class which does the validation first.
require 'date'
class Mydate
def self.strptime(string)
raise ArgumentError 'Fail' if string !~ /^\d\d\d\d-\d\d-\d\d$/
Date.strptime(string)
end
end
d = Mydate.strptime '2001-01-01'
puts d
d2 = Mydate.strptime '2001-01-02xxxx'
puts d2
Another way would be to open up the Date class, alias the strptime method, write a new one to do the validation you require and then call the aliased one.
require 'date'
class Date
class << self
alias :orig_strptime :strptime
end
def self.strptime(string)
puts "in new strptime"
raise ArgumentError 'Fail' if string !~ /^\d\d\d\d-\d\d-\d\d$/
Date.orig_strptime(string)
end
end
d = Date.strptime '2001-01-01'
puts d
d2 = Date.strptime '2001-01-02xxxx'
puts d2

Related

Ruby Time.parse incorrectly returns timestamp for String

I am facing a weird bug (?) in Ruby
Time.parse("David").to_i returns "no time information in "David"`
Time.parse("David1").to_i returns "no time information in "David1"`
However
Time.parse("David10").to_i returns 1570654800
It seems that any string with more than 2 numbers at the end manages to pass the Time conversion in Ruby. Is this a bug?
I am trying to create a single method than can handle conversion of strings to Timestamps where relevant or simply back to strings if conversion is not possible but for instances where my string includes 2+ numbers, it fails
if value.is_a? String
# if it's string of a date format
begin
Time.parse(value).to_i
rescue StandardError => e
value.downcase
end
# it's another object type - probably DateTime, Time or Date
else
value.nil? ? 0 : value.to_f
end
Internally time.rb uses, following,
def parse(date, now=self.now)
comp = !block_given?
d = Date._parse(date, comp)
year = d[:year]
year = yield(year) if year && !comp
make_time(date, year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
end
It used to parse day, month later year by precision, Range of digits when exeed to 3, it consider it as year

How to reverse Date.parse()

My code:
require 'Date'
s = "I'm going away on Oct 2, 2012th"
puts Date.parse(s)
=> 2012-10-02
I want to delete the date from my strings, that I found with Date.parse(s). The problem is, I know that there is a date, but not how it was written in the string. I know that Date.parse found it and converted "2012-10-02" to a new format.
Here is a quick and dirty solution. The function date_string
returns just the portion of the string containing the date
found by parse.
require 'date'
DATE_ERROR = -1
# If the string doesn't contain a date, it raises an
# exception. This little helper routine catches the
# exception.
def get_date(s)
date = 0
begin
date = Date.parse(s)
rescue
date = DATE_ERROR
end
date
end
# Returns just the part of the string containing the date
def date_string(s)
# First, find the date contained in the string
date = get_date(s)
return "" if date == DATE_ERROR
# Repeatedly chop off characters from the front to find the
# start of the date
first = 1
while date == get_date(s[first..-1])
first += 1
end
# Repeatedly chop off characters from the end to find the
# end of the date
last = s.length - 2
while date == get_date(s[0..last])
last -= 1
end
#Return just the date
s[first - 1..last + 1]
end
puts date_string("I'm going away on Oct 2, 2012th")
puts date_string("I'm going away on 10/2/12 and not coming back")
puts date_string("10 Nov 1999")
puts date_string("I see no date here")
This outputs:
Oct 2, 2012
10/2/12
10 Nov 1999
So you could do something like:
s = "I'm going away on Oct 2, 2012th"
datestr = date_string(s)
s.gsub!(datestr, "")
puts s
Date doesn't appear to be able to tell you where it found the date. You're probably going to have to write your own custom date finder.

Iterating over days in Ruby

I've tried the following:
def next_seven_days
today = Date.today
(today .. today + 7).each { |date| puts date }
end
But this just gives me the first and last date. I can't figure out how to get all the ones in between.
I was trying to follow the example here: http://www.whynotwiki.com/Ruby_/_Dates_and_times
I think you want something more like this:
def next_seven_days
today = Date.today
(today .. today + 7).inject { |init, date| "#{init} #{date}" }
end
In this case, the return value is a concatenated string containing all the dates.
Alternatively, if it's not a concatenated string you want, you could change the "#{init} #{date}" part of it.
As a side note, using puts in ruby on rails won't print to the web page. When you use <%= next_seven_days %>, the return value of that function is what will be printed to the page. The each function returns the range in parentheses.
Your code will definitely print all eight days to stdout. Your problem is that you're looking at the return value (which since each returns self will be (today .. today + 7)).
Note that if you print to stdout inside an erb template, that won't cause the output to show up in the rendered template.
Your function RETURNS an enumeration designated by 2011-07-07..2011-07-14 which is displayed in your view, but your puts prints to STDOUT which is not going to be your view, but the console screen your server is running in =)
If you want your view to show a list of the seven days, you need to actually create the string that does that and RETURN that :)
def next_seven_days
outputstr = ""
today = Date.today
(today..(today+7.days)).each { |date| outputstr += date.to_s }
return outputstr
end
def next_seven_days
today = Date.today
(today..(today+7.days)).each { |date| puts date }
end
Use the "next" method
def next_seven_days
today= Date.today
7.times do
puts today
today=today.next
end
end

How do I convert a String object into a Hash object?

I have a string which looks like a hash:
"{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }"
How do I get a Hash out of it? like:
{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }
The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.
For different string, you can do it without using dangerous eval method:
hash_as_string = "{\"0\"=>{\"answer\"=>\"1\", \"value\"=>\"No\"}, \"1\"=>{\"answer\"=>\"2\", \"value\"=>\"Yes\"}, \"2\"=>{\"answer\"=>\"3\", \"value\"=>\"No\"}, \"3\"=>{\"answer\"=>\"4\", \"value\"=>\"1\"}, \"4\"=>{\"value\"=>\"2\"}, \"5\"=>{\"value\"=>\"3\"}, \"6\"=>{\"value\"=>\"4\"}}"
JSON.parse hash_as_string.gsub('=>', ':')
Quick and dirty method would be
eval("{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }")
But it has severe security implications.
It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.
The string created by calling Hash#inspect can be turned back into a hash by calling eval on it. However, this requires the same to be true of all of the objects in the hash.
If I start with the hash {:a => Object.new}, then its string representation is "{:a=>#<Object:0x7f66b65cf4d0>}", and I can't use eval to turn it back into a hash because #<Object:0x7f66b65cf4d0> isn't valid Ruby syntax.
However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.
I had the same problem. I was storing a hash in Redis. When retrieving that hash, it was a string. I didn't want to call eval(str) because of security concerns. My solution was to save the hash as a json string instead of a ruby hash string. If you have the option, using json is easier.
redis.set(key, ruby_hash.to_json)
JSON.parse(redis.get(key))
TL;DR: use to_json and JSON.parse
Maybe YAML.load ?
The solutions so far cover some cases but miss some (see below). Here's my attempt at a more thorough (safe) conversion. I know of one corner case which this solution doesn't handle which is single character symbols made up of odd, but allowed characters. For example {:> => :<} is a valid ruby hash.
I put this code up on github as well. This code starts with a test string to exercise all the conversions
require 'json'
# Example ruby hash string which exercises all of the permutations of position and type
# See http://json.org/
ruby_hash_text='{"alpha"=>{"first second > third"=>"first second > third", "after comma > foo"=>:symbolvalue, "another after comma > foo"=>10}, "bravo"=>{:symbol=>:symbolvalue, :aftercomma=>10, :anotheraftercomma=>"first second > third"}, "charlie"=>{1=>10, 2=>"first second > third", 3=>:symbolvalue}, "delta"=>["first second > third", "after comma > foo"], "echo"=>[:symbol, :aftercomma], "foxtrot"=>[1, 2]}'
puts ruby_hash_text
# Transform object string symbols to quoted strings
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')
# Transform object string numbers to quoted strings
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')
# Transform object value symbols to quotes strings
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')
# Transform array value symbols to quotes strings
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')
# Transform object string object value delimiter to colon delimiter
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')
puts ruby_hash_text
puts JSON.parse(ruby_hash_text)
Here are some notes on the other solutions here
#Ken Bloom and #Toms Mikoss's solutions use eval which is too scary for me (as Toms rightly points out).
#zolter's solution works if your hash has no symbols or numeric keys.
#jackquack's solution works if there are no quoted strings mixed in with the symbols.
#Eugene's solution works if your symbols don't use all the allowed characters (symbol literals have a broader set of allowed characters).
#Pablo's solution works as long as you don't have a mix of symbols and quoted strings.
This short little snippet will do it, but I can't see it working with a nested hash. I think it's pretty cute though
STRING.gsub(/[{}:]/,'').split(', ').map{|h| h1,h2 = h.split('=>'); {h1 => h2}}.reduce(:merge)
Steps
1. I eliminate the '{','}' and the ':'
2. I split upon the string wherever it finds a ','
3. I split each of the substrings that were created with the split, whenever it finds a '=>'. Then, I create a hash with the two sides of the hash I just split apart.
4. I am left with an array of hashes which I then merge together.
EXAMPLE INPUT: "{:user_id=>11, :blog_id=>2, :comment_id=>1}"
RESULT OUTPUT: {"user_id"=>"11", "blog_id"=>"2", "comment_id"=>"1"}
I prefer to abuse ActiveSupport::JSON. Their approach is to convert the hash to yaml and then load it. Unfortunately the conversion to yaml isn't simple and you'd probably want to borrow it from AS if you don't have AS in your project already.
We also have to convert any symbols into regular string-keys as symbols aren't appropriate in JSON.
However, its unable to handle hashes that have a date string in them (our date strings end up not being surrounded by strings, which is where the big issue comes in):
string = '{'last_request_at' : 2011-12-28 23:00:00 UTC }'
ActiveSupport::JSON.decode(string.gsub(/:([a-zA-z])/,'\\1').gsub('=>', ' : '))
Would result in an invalid JSON string error when it tries to parse the date value.
Would love any suggestions on how to handle this case
works in rails 4.1 and support symbols without quotes {:a => 'b'}
just add this to initializers folder:
class String
def to_hash_object
JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
end
end
Please consider this solution. Library+spec:
File: lib/ext/hash/from_string.rb:
require "json"
module Ext
module Hash
module ClassMethods
# Build a new object from string representation.
#
# from_string('{"name"=>"Joe"}')
#
# #param s [String]
# #return [Hash]
def from_string(s)
s.gsub!(/(?<!\\)"=>nil/, '":null')
s.gsub!(/(?<!\\)"=>/, '":')
JSON.parse(s)
end
end
end
end
class Hash #:nodoc:
extend Ext::Hash::ClassMethods
end
File: spec/lib/ext/hash/from_string_spec.rb:
require "ext/hash/from_string"
describe "Hash.from_string" do
it "generally works" do
[
# Basic cases.
['{"x"=>"y"}', {"x" => "y"}],
['{"is"=>true}', {"is" => true}],
['{"is"=>false}', {"is" => false}],
['{"is"=>nil}', {"is" => nil}],
['{"a"=>{"b"=>"c","ar":[1,2]}}', {"a" => {"b" => "c", "ar" => [1, 2]}}],
['{"id"=>34030, "users"=>[14105]}', {"id" => 34030, "users" => [14105]}],
# Tricky cases.
['{"data"=>"{\"x\"=>\"y\"}"}', {"data" => "{\"x\"=>\"y\"}"}], # Value is a `Hash#inspect` string which must be preserved.
].each do |input, expected|
output = Hash.from_string(input)
expect([input, output]).to eq [input, expected]
end
end # it
end
Here is a method using whitequark/parser which is safer than both gsub and eval methods.
It makes the following assumptions about the data:
Hash keys are assumed to be a string, symbol, or integer.
Hash values are assumed to be a string, symbol, integer, boolean, nil, array, or a hash.
# frozen_string_literal: true
require 'parser/current'
class HashParser
# Type error is used to handle unexpected types when parsing stringified hashes.
class TypeError < ::StandardError
attr_reader :message, :type
def initialize(message, type)
#message = message
#type = type
end
end
def hash_from_s(str_hash)
ast = Parser::CurrentRuby.parse(str_hash)
unless ast.type == :hash
puts "expected data to be a hash but got #{ast.type}"
return
end
parse_hash(ast)
rescue Parser::SyntaxError => e
puts "error parsing hash: #{e.message}"
rescue TypeError => e
puts "unexpected type (#{e.type}) encountered while parsing: #{e.message}"
end
private
def parse_hash(hash)
out = {}
hash.children.each do |node|
unless node.type == :pair
raise TypeError.new("expected child of hash to be a `pair`", node.type)
end
key, value = node.children
key = parse_key(key)
value = parse_value(value)
out[key] = value
end
out
end
def parse_key(key)
case key.type
when :sym, :str, :int
key.children.first
else
raise TypeError.new("expected key to be either symbol, string, or integer", key.type)
end
end
def parse_value(value)
case value.type
when :sym, :str, :int
value.children.first
when :true
true
when :false
false
when :nil
nil
when :array
value.children.map { |c| parse_value(c) }
when :hash
parse_hash(value)
else
raise TypeError.new("value of a pair was an unexpected type", value.type)
end
end
end
and here are some rspec tests verifying that it works as expected:
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe HashParser do
describe '#hash_from_s' do
subject { described_class.new.hash_from_s(input) }
context 'when input contains forbidden types' do
where(:input) do
[
'def foo; "bar"; end',
'`cat somefile`',
'exec("cat /etc/passwd")',
'{:key=>Env.fetch("SOME_VAR")}',
'{:key=>{:another_key=>Env.fetch("SOME_VAR")}}',
'{"key"=>"value: #{send}"}'
]
end
with_them do
it 'returns nil' do
expect(subject).to be_nil
end
end
end
context 'when input cannot be parsed' do
let(:input) { "{" }
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'with valid input' do
using RSpec::Parameterized::TableSyntax
where(:input, :expected) do
'{}' | {}
'{"bool"=>true}' | { 'bool' => true }
'{"bool"=>false}' | { 'bool' => false }
'{"nil"=>nil}' | { 'nil' => nil }
'{"array"=>[1, "foo", nil]}' | { 'array' => [1, "foo", nil] }
'{foo: :bar}' | { foo: :bar }
'{foo: {bar: "bin"}}' | { foo: { bar: "bin" } }
end
with_them do
specify { expect(subject).to eq(expected) }
end
end
end
end
I built a gem hash_parser that first checks if a hash is safe or not using ruby_parser gem. Only then, it applies the eval.
You can use it as
require 'hash_parser'
# this executes successfully
a = "{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' },
:key_b => { :key_1b => 'value_1b' } }"
p HashParser.new.safe_load(a)
# this throws a HashParser::BadHash exception
a = "{ :key_a => system('ls') }"
p HashParser.new.safe_load(a)
The tests in https://github.com/bibstha/ruby_hash_parser/blob/master/test/test_hash_parser.rb give you more examples of the things I've tested to make sure eval is safe.
This method works for one level deep hash
def convert_to_hash(str)
return unless str.is_a?(String)
hash_arg = str.gsub(/[^'"\w\d]/, ' ').squish.split.map { |x| x.gsub(/['"]/, '') }
Hash[*hash_arg]
end
example
> convert_to_hash("{ :key_a => 'value_a', :key_b => 'value_b', :key_c => '' }")
=> {"key_a"=>"value_a", "key_b"=>"value_b", "key_c"=>""}
I came to this question after writing a one-liner for this purpose, so I share my code in case it helps somebody. Works for a string with only one level depth and possible empty values (but not nil), like:
"{ :key_a => 'value_a', :key_b => 'value_b', :key_c => '' }"
The code is:
the_string = '...'
the_hash = Hash.new
the_string[1..-2].split(/, /).each {|entry| entryMap=entry.split(/=>/); value_str = entryMap[1]; the_hash[entryMap[0].strip[1..-1].to_sym] = value_str.nil? ? "" : value_str.strip[1..-2]}
Ran across a similar issue that needed to use the eval().
My situation, I was pulling some data from an API and writing it to a file locally. Then being able to pull the data from the file and use the Hash.
I used IO.read() to read the contents of the file into a variable. In this case IO.read() creates it as a String.
Then used eval() to convert the string into a Hash.
read_handler = IO.read("Path/To/File.json")
puts read_handler.kind_of?(String) # Returns TRUE
a = eval(read_handler)
puts a.kind_of?(Hash) # Returns TRUE
puts a["Enter Hash Here"] # Returns Key => Values
puts a["Enter Hash Here"].length # Returns number of key value pairs
puts a["Enter Hash Here"]["Enter Key Here"] # Returns associated value
Also just to mention that IO is an ancestor of File. So you can also use File.read instead if you wanted.
I had a similar issue when trying to convert a string to a hash in Ruby.
The result from my computations was this:
{
"coord":{"lon":24.7535,"lat":59.437},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],
"base":"stations",
"main":{"temp":283.34,"feels_like":281.8,"temp_min":282.33,"temp_max":283.34,"pressure":1021,"humidity":53},
"visibility":10000,
"wind":{"speed":3.09,"deg":310},
"clouds":{"all":75},
"dt":1652808506,
"sys":{"type":1,"id":1330,"country":"EE","sunrise":1652751796,"sunset":1652813502},
"timezone":10800,"id":588409,"name":"Tallinn","cod":200
}
I checked the type value and confirmed that it was of the String type using the command below:
result =
{
"coord":{"lon":24.7535,"lat":59.437},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],
"base":"stations",
"main":{"temp":283.34,"feels_like":281.8,"temp_min":282.33,"temp_max":283.34,"pressure":1021,"humidity":53},
"visibility":10000,
"wind":{"speed":3.09,"deg":310},
"clouds":{"all":75},
"dt":1652808506,
"sys":{"type":1,"id":1330,"country":"EE","sunrise":1652751796,"sunset":1652813502},
"timezone":10800,"id":588409,"name":"Tallinn","cod":200
}
puts result.instance_of? String
puts result.instance_of? Hash
Here's how I solved it:
All I had to do was run the command below to convert it from a String to a Hash:
result_new = JSON.parse(result, symbolize_names: true)
And then checked the type value again using the commands below:
puts result_new.instance_of? String
puts result_new.instance_of? Hash
This time it returned true for the Hash

Safe integer parsing in Ruby

I have a string, say '123', and I want to convert it to the integer 123.
I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all.
EDIT: I was looking for the standard way of doing it, without regex trickery.
Ruby has this functionality built in:
Integer('1001') # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
As noted in answer by Joseph Pecoraro, you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.
Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:
Integer('23') # => 23
Integer('0x23') # => 35
Integer('023') # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10) # => 23
This might work:
i.to_i if i.match(/^\d+$/)
Also be aware of the affects that the current accepted solution may have on parsing hex, octal, and binary numbers:
>> Integer('0x15')
# => 21
>> Integer('0b10')
# => 2
>> Integer('077')
# => 63
In Ruby numbers that start with 0x or 0X are hex, 0b or 0B are binary, and just 0 are octal. If this is not the desired behavior you may want to combine that with some of the other solutions that check if the string matches a pattern first. Like the /\d+/ regular expressions, etc.
Another unexpected behavior with the accepted solution (with 1.8, 1.9 is ok):
>> Integer(:foobar)
=> 26017
>> Integer(:yikes)
=> 26025
so if you're not sure what is being passed in, make sure you add a .to_s.
I like Myron's answer but it suffers from the Ruby disease of "I no longer use Java/C# so I'm never going to use inheritance again". Opening any class can be fraught with danger and should be used sparingly, especially when it's part of Ruby's core library. I'm not saying don't ever use it, but it's usually easy to avoid and that there are better options available, e.g.
class IntegerInString < String
def initialize( s )
fail ArgumentError, "The string '#{s}' is not an integer in a string, it's just a string." unless s =~ /^\-?[0-9]+$/
super
end
end
Then when you wish to use a string that could be a number it's clear what you're doing and you don't clobber any core class, e.g.
n = IntegerInString.new "2"
n.to_i
# => 2
IntegerInString.new "blob"
ArgumentError: The string 'blob' is not an integer in a string, it's just a string.
You can add all sorts of other checks in the initialize, like checking for binary numbers etc. The main thing though, is that Ruby is for people and being for people means clarity. Naming an object via its variable name and its class name makes things much clearer.
I had to deal with this in my last project, and my implementation was similar, but a bit different:
class NotAnIntError < StandardError
end
class String
def is_int?
self =~ /^-?[0-9]+$/
end
def safe_to_i
return self.to_i if is_int?
raise NotAnIntError, "The string '#{self}' is not a valid integer.", caller
end
end
class Integer
def safe_to_i
return self
end
end
class StringExtensions < Test::Unit::TestCase
def test_is_int
assert "98234".is_int?
assert "-2342".is_int?
assert "02342".is_int?
assert !"+342".is_int?
assert !"3-42".is_int?
assert !"342.234".is_int?
assert !"a342".is_int?
assert !"342a".is_int?
end
def test_safe_to_i
assert 234234 == 234234.safe_to_i
assert 237 == "237".safe_to_i
begin
"a word".safe_to_i
fail 'safe_to_i did not raise the expected error.'
rescue NotAnIntError
# this is what we expect..
end
end
end
someString = "asdfasd123"
number = someString.to_i
if someString != number.to_s
puts "oops, this isn't a number"
end
Probably not the cleanest way to do it, but should work.
Re: Chris's answer
Your implementation let's things like "1a" or "b2" through. How about this instead:
def safeParse2(strToParse)
if strToParse =~ /\A\d+\Z/
strToParse.to_i
else
raise Exception
end
end
["100", "1a", "b2", "t"].each do |number|
begin
puts safeParse2(number)
rescue Exception
puts "#{number} is invalid"
end
end
This outputs:
100
1a is invalid
b2 is invalid
t is invalid

Resources