Full string scan in Ruby String

Is there a Ruby equivalent for a Java scanner?

If I have a line like "hi 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 do you do this in Ruby?

+4
source share
2 answers

Several assignments from arrays may be useful for this.

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

Less effective alternative:

 a,b,c,d = sc.split.map{|w| Integer(w) rescue w} 
+7
source

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 need 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" 
+12
source

All Articles