Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby String Integer Scanning

Is there a Ruby equivalent of the Java Scanner?

If I have a string like "hello 123 hi 234"

In Java I could do

Scanner sc = new Scanner("hello 123 hi 234");
String a = sc.nextString();
int b = sc.nextInt();
String c = sc.nextString();
int d = sc.nextInt();

How would you do this in Ruby?

like image 511
Verhogen Avatar asked Dec 02 '22 06:12

Verhogen


2 Answers

Use String.scan:


>> s = "hello 123 hi 234"
=> "hello 123 hi 234"
>> s.scan(/\d+/).map{|i| i.to_i}
=> [123, 234]

RDoc here

If you want something closer to the Java implementation, you can use StringScanner:


>> require 'strscan'
 => true
>> s = StringScanner.new "hello 123 hi 234"
=> # &lt StringScanner 0/16 @ "hello...">
>> s.scan(/\w+/)
=> "hello"
>> s.scan(/\s+/)
=> " "
>> s.scan(/\d+/)
=> "123"
>> s.scan_until(/\w+/)
=> " hi"
>> s.scan_until(/\d+/)
=> " 234"
like image 115
klochner Avatar answered Dec 03 '22 19:12

klochner


Multiple assignment from arrays can be useful for this

a,b,c,d = sc.split
b=b.to_i
d=d.to_i

A less efficient alternative:

a,b,c,d = sc.split.map{|w| Integer(w) rescue w}
like image 34
Jonas Elfström Avatar answered Dec 03 '22 20:12

Jonas Elfström