JohnGalt
JohnGalt

Reputation: 2881

Ruby while loop within if statement

Using the following code in Ruby:

if (tickFormat.length > 12 && tickFormat.length < 24)
    i = 1
    while(i < tickFormat.length) do
        if (i%2 != 0)
          tickFormat.at(i)[1] = ''
        end
        i++
    end
end

I get an "unexpected keyword_end" for the 2nd "end" statement. If I remove the while loop the code runs without error. Any ideas?

Upvotes: 3

Views: 7136

Answers (5)

2called-chaos
2called-chaos

Reputation: 3078

You're obviously from the C corner so some additional info from my side:

First I would like to quote Alexey Anufriyev

I think you should use naming convention adopted by your platform. underscore_case will look weird in C# code, as camelCase in Ruby =)

So you should consider using underscore notation.

Also you're code is pretty C style. This is a bit more ruby like (though it is a matter of taste whether you write short statements in the same line or not):

if tick_format.length === (13..23)
  tick_format.each_with_index do |tf, i|
    tf[1] = '' if i.odd?
  end
end

# if you use active support's core extensions (which is recommended imho)
# you can rewrite line 1 as:
if tick_format.length.in? 13..23

Upvotes: 3

dimuch
dimuch

Reputation: 12818

Ruby has too much sugar to code it C-style :)

Try something like

if tickFormat.length.between?(13,23)
  (1..tickFormat.length).step(2) do |i|
    tickFormat.at(i)[1] = ''
  end
end

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146043

The only thing wrong is the i++. I might suggest migrating the style a bit from C-like to canonical-Ruby, but that's just a personal choice...

if (13..23) === tickFormat.length
  i = 1
  while i < tickFormat.length
    if i % 2 != 0
      tickFormat.at(i)[1] = ''
    end
    i += 1
  end
end

Upvotes: 0

OpenCoderX
OpenCoderX

Reputation: 6318

You want to use i+=1 to increment.

if tickFormat.length > 12 && tickFormat.length < 24
        i = 1
        while i < tickFormat.length do
            if (i%2 != 0)
              tickFormat.at(i)[1] = ''
            end
            i+=1
        end
    end

Upvotes: 0

MrYoshiji
MrYoshiji

Reputation: 54882

Try this:

if (tickFormat.length > 12 && tickFormat.length < 24)
  i = 1
  while(i < tickFormat.length) do
    if (i%2 != 0)
      tickFormat.at(i)[1] = ''
    end
    i += 1
  end
end

The i++ syntax doesn't work in Ruby

Upvotes: 3

Related Questions