From: Mike Stok Date: 2006-05-12T12:20:48+09:00 Subject: Re: conversion issues On 11-May-06, at 10:57 PM, corey konrad wrote: > yeah i like your way alot better than num = Integer(STDIN.gets) rescue > nil > > > > Guest wrote: >> corey konrad wrote: >>>> because it needs to be a string when you print it. >>> >>> oh ok that makes sense, isnt there a getn method for getting >>> number or >>> other data types or do i always have to use gets? >> >> There could be: >> >> irb(main):001:0> def getn >> irb(main):002:1> foo = gets >> irb(main):003:1> foo.to_i >> irb(main):004:1> end >> => nil That depends on how you want to handle errors, with this implementation of getn garbage input gets turned into 0 (which you may or may not want to happen.) You don't need the STDIN, or the rescue, so you can pick whichever you deem appropriate for your situation: num = gets.to_i # decimals only, bad input => 0 num = Integer(gets) # handles 0x, 0, 0b prefixes, bad input => ArgumentError num = Integer(gets) rescue nil # as above but bad input => nil And scanf is very useful for a raft of more complex cases (where you might want a C style scanf :-) What is appropriate depends on what you are trying to do. Mike -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.