4

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?

1
  • 6
    This sounds like a half-step. In Ruby, half-steps tend to disappear completely. What do you -want- to do ? Commented Jan 19, 2010 at 16:39

2 Answers 2

12

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"
Sign up to request clarification or add additional context in comments.

Comments

7

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}

8 Comments

That would be total genius if Ruby could determine a and c were strings and b and d were integers. Still close enough for me to have learnt something!
In the Java example, the programmer has to know which words are expected to be integers, so there's nothing wrong with a Ruby solution relying upon that requirement. And this -is- prettier than either of my solutions.
@Pongus: The question already specifies that a and c are strings and b and d are integers, so what's wrong with relying on that?
Wow. That one-liner is just elegant. +1 from me.
@Jörg: I didnt mean for it to sound like I was complaining, I would have just been doubly impressed if Ruby had worked that out for us. Still +1. Would have been +2 since the edit if I could. :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.