From: Robert Klemme Date: 2011-08-16T00:16:46+09:00 Subject: Re: A Corresponding between C++ AND Ruby On Fri, Aug 12, 2011 at 6:35 PM, David Masover wrote: > On Friday, August 12, 2011 09:02:36 AM Dave Baldwin wrote: >> On 12 Aug 2011, at 14:10, amir a. wrote: >> > 2 - int a,b,c,d; >> > >> >    while( 1 ) { >> > >> >       cin >> a >> b >> c >>d ; >> >       if( a < 0 || b < 0 ) >> > >> >          break; >> > >> >       cout << a << " " << b << " " << c << " " << d << endl; >> > >> >    } >> >> while true >>       a, b, c, d = gets.split.map {|s| s.to_i} >>       break if a < 0 || b < 0 >>       STDOUT << a << " " << b << " " << c << " " << d << "\n"; >> end > > A nitpick: This doesn't do exactly the same thing. The 'cin' version, if I > understand it, will read the next four things which look like integers, > separated by any whitespace, including newlines. It only seems like it > operates per-line since that's how you'd manually enter text into stdin, but > the program actually sees it as an unbroken stream. So you can enter each > number on its own line, or eight of them on the same line... > > The gets version will read a single line. If there aren't enough integers, > some variables will be nil. If there are too many, some integers will be > ignored, not carried over to the next line. This can be fixed with a construction similar to this $ ruby19 -e 'n=[];loop do while(n.size < 4);n.concat(gets.scan(/\d+/).map(&:to_i)) end;a=n.slice!(0,4); p a; end' 1 2 3 4 5 6 [1, 2, 3, 4] 7 8 [5, 6, 7, 8] 6 5 4 3 2 1 [6, 5, 4, 3] 0 1 [2, 1, 0, 1] -e:1:in `block in
': undefined method `scan' for nil:NilClass (NoMethodError) from -e:1:in `loop' from -e:1:in `
' :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/