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?
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"
=> # < 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"
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With