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.
source to share
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.
source to share
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
source to share
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?
source to share