For loops trouble

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[i] < x;i++)
I tried this
for i in a[i]…x
but it produce some errors. Any help will be appreciated. Thank you.

On Sat, Apr 16, 2011 at 1:27 PM, Daniel J.
[email protected]wrote:

numbers = *1…10
max = 6

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

On Sat, Apr 16, 2011 at 1:36 PM, Josh C. [email protected]
wrote:

Posted via http://www.ruby-forum.com/.

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|

On Sat, Apr 16, 2011 at 11:27 AM, Daniel J.
[email protected] wrote:

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[i] < x;i++)
I tried this
for i in a[i]…x
but it produce some errors. Any help will be appreciated. Thank you.

A simple literal translation goes from this:

for (int i=0; a[i] < x; i++) { … }

to this Ruby:

i = 0
while a[i] < x

i += 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.

On Sun, Apr 17, 2011 at 2:27 AM, Daniel J. [email protected]
wrote:

for(int i = 0; a[i] < x;i++)

there are many ways.
eg,

x
=> 6
a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.take_while{|e| e<x}
=> [1, 2, 3, 4, 5]
a.each_with_index.take_while{|e| e<x}
=> [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4]]

kind regards -botp

Daniel J. 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[i] < x;i++)
I tried this
for i in a[i]…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 call each()
directly:

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

I tried this
for i in a[i]…x

If a[i] = 4, and x = 7, then you are traversing the range 4…7. Also,
your variable names would cause confusion: i for the element and i for
the index.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs