For loops trouble

D

Daniel Johnson

I am trying to translate a program I have in Java into ruby and having
trouble translating this for loop
for(int i = 0; a < x;i++)
I tried this
for i in a...x
but it produce some errors. Any help will be appreciated. Thank you.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

I am trying to translate a program I have in Java into ruby and having
trouble translating this for loop
for(int i = 0; a < x;i++)
I tried this
for i in a...x
but it produce some errors. Any help will be appreciated. Thank you.

numbers = *1..10
max = 6

numbers.each do |num|
break unless num < max
puts num
end
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

I am trying to translate a program I have in Java into ruby and having
trouble translating this for loop
for(int i = 0; a < x;i++)
I tried this
for i in a...x
but it produce some errors. Any help will be appreciated. Thank you.

numbers = *1..10
max = 6

numbers.each do |num|
break unless num < max
puts num
end



I guess, depending on your needs, you might want the index as well, in which
case

numbers.each do |num|

becomes

numbers.each_with_index do |num, index|
 
7

7stud --

Daniel Johnson wrote in post #993238:
I am trying to translate a program I have in Java into ruby and having
trouble translating this for loop
for(int i = 0; a < x;i++)
I tried this
for i in a...x
but it produce some errors. Any help will be appreciated. Thank you.


Ruby has a for-in loop:

a = [2, 4, 1, 9, 6]
x = 7

for num in a
break if num > x
puts num
end

But a for-in loop calls each(), so ruby programmers just use each()
directly:

a.each do |num|
break if num > x
puts num
end
 
C

Christopher Dicely

I am trying to translate a program I have in Java into ruby and having
trouble translating this for loop
=C2=A0 for(int i =3D 0; a < x;i++)
I tried this
=C2=A0 for i in a...x
but it produce some errors. Any help will be appreciated. Thank you.


A simple literal translation goes from this:

for (int i=3D0; a < x; i++) { ... }

to this Ruby:

i =3D 0
while a < x
...
i +=3D 1
end

That Ruby is almost certainly not the best way to translate the Java
loop, but the best way really depends on what you are doing in the
loop.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,057
Members
48,769
Latest member
Clifft

Latest Threads

Top