views:

233

answers:

2

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?

+6  A: 

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}
Jonas Elfström
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!
Mongus Pong
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.
Wayne Conrad
@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?
Jörg W Mittag
Wow. That one-liner is just elegant. +1 from me.
Wayne Conrad
@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. :-)
Mongus Pong
It's pity that none of the downvoters commented on why.
Jonas Elfström
I'll upvote if you change 'not as performant' to 'less efficient'
klochner
Haha, it's a deal!
Jonas Elfström
An integer-detecting version that doesn't rely on exceptions (possibly faster — haven't profiled): `a,b,c,d = sc.split.map {|w| w.empty? || w =~ /\D/ ? w : w.to_i}`
Chuck
@chuck - depends on the density of integers
klochner
+6  A: 
klochner