[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Best way to call Integer on temporary?
From:       Robert Klemme <shortcutter () googlemail ! com>
Date:       2017-02-26 12:58:31
Message-ID: CAM9pMnM3SS9V0GFdUbKuo=RGsneD2qxGfqm77=MkfTMi_7n-Ow () mail ! gmail ! com
[Download RAW message or body]

On Sun, Feb 26, 2017 at 1:53 PM, Robert Klemme
<shortcutter@googlemail.com> wrote:
> On Sun, Feb 26, 2017 at 8:25 AM, botp <botpena@gmail.com> wrote:
>> On Wed, Feb 22, 2017 at 9:28 AM, Samuel Williams
>> <space.ship.traveller@gmail.com> wrote:
>>> 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.
>>
>> if you like exceptions, then you also like rescuing.
>>
>> you may start with the shorter modifier form of rescuing,
>> eg,
>>
>> result = Integer foo rescue bar
>
> I don't think that cuts it because you still want to see an exception
> if the input is ill formed. At least I would.

Thinking a bit more about this there is a different approach: since
OptionParser does support type safe conversions you could also do this
during command line argument parsing:

irb(main):009:0> options = {foo: 0}
=> {:foo=>0}
irb(main):010:0> OptionParser.new {|o| o.on("--foo=VAL",
Integer){|v|options[:foo]=v}}.parse %w{--foo 77}
=> []
irb(main):011:0> options
=> {:foo=>77}
irb(main):012:0> OptionParser.new {|o| o.on("--foo=VAL",
Integer){|v|options[:foo]=v}}.parse %w{--foo ab}
OptionParser::InvalidArgument: invalid argument: --foo ab
from (irb):12
from /usr/bin/irb:11:in `<main>'

Kind regards

robert

-- 
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic