The challenge in understanding ruby ​​C-style loops

I find it .each do

hard to get, so I was hoping for regular use of C syntax for a loop, which doesn't seem to work, so I tried for a while but still get errors.

I've tried this.

i = 0
while i < SampleCount
    samples[i] = amplitude
    amplitude *= -1
    i++
end

      

I am getting complaints about the end operator here.

+2


source to share


5 answers


There are several problems with the code. Rather than just fixing mistakes, I would suggest that you study the ruby ​​path more long term - it will save you time and energy later. In this case it is

5.times do |i|
  samples[i] = amplitude  # assumes samples already exists and has 5 entries.
  amplitude *= -1
end

      

If you insist on keeping this style, you can do this:



samples = []
i = 0
while i < sample_count
    samples << amplitude  # add new item to array.
    amplitude *= -1
    i += 1                # you can't use ++.
end

      

Note that the SampleCount

initial capital letter, by Ruby convention, means a constant, which I assume is not what you really mean.

+8


source


I agree with Peter that there are other (more idiomatic) ways to do this in Ruby, but just to be clear: the error message you saw is misdirected at you. There while

was nothing wrong with your loop . The problem was i++

because there is no operator in Ruby ++

.

This will do pretty well:

limit = 10

i = 0
while i < limit
    puts i
    i += 1
end

      



Again, I don't recommend this, but if you are just learning the language it might help you find out where the problem really is.

Ruby has many built-in ways of repeating other than for

or while

(which, as I can tell, is most often seen). Several other examples:

(1..10).each do |x| # 1..10 is a range which you can iterate over with each
  puts x
end

1.upto(10) { |x| puts x } # Integers have upto and downto methods that can be useful

      

+2


source


You originally mentioned trying to use a for loop. Despite various other comments in the answers, here's the approach for a loop:

for i in 0...5
  samples[i] = amplitude
  amplitude *= -1
end

      

+1


source


No one here has come up with an alternative solution that actually does what Fred originally intended - and this is repeated around the value of the SampleCount constant. This is how you could do:

SampleCount.times do |i|

      

Or:

limit = SampleCount
limit.times do |i|

      

Or:

for i in 0..SampleCount

      

Could any of these be Ruby-esque enough?

0


source


The end operator issue is related to i++

. Ruby wants to add something. Ruby does not have an increment operator. You need to use i += 1

. With this change, you can use your C loop as is.

0


source







All Articles