是否有与Java Scanner相当的Ruby?
如果我有一个字符串,如“hello 123 hi 234”
在Java中,我可以做到
Scanner sc = new Scanner("hello 123 hi 234");
String a = sc.nextString();
int b = sc.nextInt();
String c = sc.nextString();
int d = sc.nextInt();
你会如何在Ruby中做到这一点?
答案 0 :(得分:12)
使用String.scan
:
>> s = "hello 123 hi 234"
=> "hello 123 hi 234"
>> s.scan(/\d+/).map{|i| i.to_i}
=> [123, 234]
RDoc here
如果您想要更接近Java实现的东西,可以使用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"
答案 1 :(得分:7)
数组的多次赋值对此
非常有用a,b,c,d = sc.split
b=b.to_i
d=d.to_i
效率较低的替代方案:
a,b,c,d = sc.split.map{|w| Integer(w) rescue w}