How to use for in Ruby?

Asked

Viewed 555 times

-2

I can’t use the for equal use in the Java.

I am trying to find out if a die is addicted. An honest casino owner launched it n times, given the n Launch results, determine the number of occurrences of each side.

  • Please show the code you are trying to run, so that other users understand the problem better.

2 answers

2

The syntax of for in Ruby is:

for «variável» in «lista»
    «comandos»
end

To make a loop that goes from 0 to 9 (10 repetitions), something equivalent to for(i=0; i<10; i++), you will do:

for i in 0..9
    puts "o valor de 'i' é #{x}"
end

And if you want, you can use a variable to indicate the limit of your loop:

n=9
for i in 0..n
    puts "o valor de 'i' é #{x}"
end

If you don’t want to include the last value, use ... instead of ... In this case you will get the same result using 0..9 or 0...10.

  • It just got me confused if 0..n for n = 10 has the same behavior of using the constant 0..9 ; at least as it appeared in its text

  • 1

    Oops, it was supposed to be n=9, my mistake. I’ll fix it.

1

Rubists are not fans of explicit ties like for and while.

It is very common to see loops using iterators, as does the Array#each:

a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
=> a -- b -- c --

Or even using the Integer#times:

5.times do |i|
  print i, " "
end
#=> 0 1 2 3 4

Of course not always the each or the times solve your problem, but rarely have I had to use the for or while in Ruby.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.