开发者

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开发者_StackOverflow社区

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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜