From: ruby-talk [mailto:ruby-talk-bounces@ruby-lang.org] On Behalf Of
Samuel
Williams
Sent: 22 February 2017 1:28 am
To: ruby-talk ML
Subject: Best way to call Integer on temporary?
I like to use Float, Integer and String to typecast data from user. It
raises an exception if the value was invalid for some reason.
However, it doesn't easily support optional values, e.g. Integer(nil)
fails too. So, I end up writing code like:
result = (tmp = x[:foo]) ? Integer(tmp) : nil
But that seems really ugly.
Is there a better way without just writing my own wrapper all the
time? It would be nice to write something like x[:foo]&.to_i, but that
doesn't raise an exception for invalid input, only returns 0 which
makes it hard to tell the difference between invalid input and "0".
It seems like you might have reached the level of complexity which might
justify a separate function: say, validate_int(foo) which either returns an
integer or raises an exception. (Or, which might be better, throws a
signal; arguably a validation fail isn't actually an exception in your
application, but an expected event.)
Don't think of it of having to write a wrapper each time. Think of it as
making your code clearer, easier to debug. After all, which is better ---
result = (tmp = x[:foo]) ? Integer(tmp) : nil
or:
result = validate_int x[:foo]
?
Yeah, if it's just the three functions, and you're reusing them enough, it
makes sense to wrap them up nicely.
If it were just a one off, and if #self took a block, you could do this:
x[:foo]&.self{|i| Integer(i) }
Right now you could get there with #tap and a hack:
x[:foo]&.tap{|i| break Integer(i) }
(I think - untested because I'm on my phone)
Cheers
···
On 22 Feb 2017 18:36, "Andy Jones" <Andy.Jones@jameshall.co.uk> wrote:
-----Original Message-----