Hi
I am C++ programmer and in C++ I used some thing that I want
corresponding those things in Ruby.
please help me.
1 - In C++ , I can write this program but in Ruby I can’t:
int i,x;
int sum=0;
for( x=0 ; x <= 50 ; x++ ) {
cin >> i;
sum = sum + ( x + i ) ;
}
cout << sum;
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;
}
On Friday, August 12, 2011 09:02:36 AM Dave B. wrote:
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.
Similar things apply to the first example.
Also, both Ruby and C++ have a higher-level construct than “\n” – why
not:
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
Hi
I am C++ programmer and in C++ I used some thing that I want
corresponding those things in Ruby.
please help me.
1 - In C++ , I can write this program but in Ruby I can’t:
int i,x;
int sum=0;
for( x=0 ; x <= 50 ; x++ ) {
cin >> i;
sum = sum + ( x + i ) ;
}
cout << sum;
A direct translation would be:
sum = 0
for x in 0…3 #Note the three dots, which excludes the endpoint
i = gets
sum = sum + (x + i.to_i)
end
print sum
But:
Experienced programmers never write:
sum = sum +…
They write:
sum += …
In ruby for() calls each(), so ruby programmers just call each()
directly:
sum = 0
(0…3).each do |i|
x = gets
sum += (i + x.to_i)
end
puts sum
And there are many ways to loop in ruby:
sum = 0
3.times do |i| #0, 1, 2
x = gets
sum += (i + x.to_i)
end
puts sum
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.