From: dblack@... Date: 2006-11-18T02:01:30+09:00 Subject: Re: Nuby question - printing substring as non-ASCII Hi -- On Sat, 18 Nov 2006, Wilson Bilkovich wrote: > On 11/17/06, Thomas Luedeke wrote: >> Thomas Luedeke wrote: >> > I'm reading in a string of numbers, as follows: >> > >> > " 1 45.3456 " >> > >> > How do I write out the first non-whitespace element as a number? Ruby >> > wants to express as it in ASCII, and the .to_i method doesn't seem to >> > work on a substring. >> > >> > Thanks in advance. >> > >> > TPL >> >> >> Thanks. Dumb question, but I'm kinda deep in the throes of the "suck" >> stage of learning Ruby. The following also seems to work (at least for >> the purposes of reading in and writing formatted output): >> >> irb(main):001:0> string=" 1 45.3456 " >> => " 1 45.3456 " >> >> irb(main):003:0> string.strip >> => "1 45.3456" >> >> irb(main):004:0> string.split[1] >> => "45.3456" >> >> irb(main):005:0> string.split[0] >> => "1" >> > > Here is one way: > irb(main):001:0> string = " 1 45.3456 " > => " 1 45.3456 " > irb(main):002:0> substrings = string.scan /[^\s]+/ > => ["1", "45.3456"] > irb(main):003:0> substrings.first.to_i > => 1 > > The second line of code is saying: Scan the string, and return an > Array of strings that were made up of one or more non-whitespace > characters. > > substrings.first is the same as substrings[0] Another possibility: irb(main):001:0> require 'scanf' => true irb(main):002:0> string = " 1 45.3456 " => " 1 45.3456 " irb(main):003:0> string.scanf("%d") => [1] You have to get it out of the array, but you don't have to convert it (it's already an integer). David -- David A. Black | dblack@rubypal.com Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org