Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem comprehending C-style ruby loops

Tags:

ruby

I find the .each do hard to get to stick, so I was hoping for regular use of C for loop syntax which seems to not work, so I tried a while but still get errors.

I have tried this.

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

I get complaints about the end statement here.

like image 795
Fred Avatar asked May 23 '26 15:05

Fred


1 Answers

There are several problems with your code. Rather than just fixing the errors, I'd suggest it's better long-term for you to learn the Ruby way - it will save you time and energy later. In this case, it's

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

If you insist on keeping a similar 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 SampleCount's initial capital letter, by Ruby convention, means a constant, which I'm guessing isn't what you really mean.

like image 185
Peter Avatar answered May 26 '26 08:05

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!