#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Very basic loop question


    Hi

    today i tried to made my first steps with ruby and tested following basic sample

    Code:
    curValue = "x\ny"
    values = curValue.split("\n")
    print values.to_s + "\n"
    
    i = 0
    while i < values.length do
    
      print "check: i=" + i.to_s + ", content=" +  values[i] + "\n"
    
      # who changed i to i+1?
      if (values[i - 1]  == "x")
        print "Why is i here " + i.to_s + " !?!?\n"
      else
        print  " -- no match of '" + values[i].to_s + "' --\n"
      end if
    
      i += 1
    end
    the output of this sample is:
    xy
    check: i=0, content=x
    Why is i here 1 !?!?
    check: i=1, content=y
    -- no match of '' --

    I can't understand why the variable i is getting i+1 in the if clause?

    Best.reg
    birdy
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,930
    Rep Power
    1045
    Hi,

    it's a syntax error: There is no "end if" in Ruby, just an end.

    The only reason your script doesn't blow up is because you happen to have the i += 1 after the misplaced if. This is read as an if modifier like in
    Code:
    print number if number.even?
    So in the end, you get a weird construct, which will increment i before checking the "inner" if statement.

    I think a general problem is that you seem to come from another language and now try to apply its syntax and programming style to Ruby. But Ruby isn't Java or C or whatever you might have been using. This "counter juggling", fumbling with string concatenation and low level stuff like while, for etc. are very rare in Ruby. Usually, you use a much more high level style employing "advanced" techniques like blocks, string interpolation and methods like each, each_line, all?, none? etc.

    For example, if you simply want to iterate over the lines of a string and output both the current index and the line, you'd do it like this:
    Code:
    text = "x\ny"
    text.each_line.with_index do |line, i|
      puts "line #{i}: #{line}"
    end
    As you can see, it's much more readable and shorter than all this "while (++i < str.length()) {yadda yadda yadda}" you'd do in Java.

    So if you want to learn Ruby, I strongly suggest that you leave aside your "old habits" you adopted from other languages and be open about a different programming style. Ruby is much closer to languages like Smalltalk or Haskell than it is to the usual run-of-the-mill "business languages" like Java or C++ or C#.

IMN logo majestic logo threadwatch logo seochat tools logo