SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member The_Big_K's Avatar
    Join Date
    May 2008
    Location
    In my home
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Problem with simple while loop

    I'm not sure what's going wrong here.

    What changes should I make to make this run?
    Code Ruby:
    class Fib	
    	def FibUpTo(max)
     
    		i1,i2 = 1,1
     
    		yield i1 <= max
    			return i1
    			i1, i2 = i2, i1+i2
    		end
    	end
    end
     
     
    newobj = Fib.new
     
    print newobj.FibUpTo(500)


    Btw, why does the code output only "1" when I replace 'yield' with 'while'?

  2. #2
    SitePoint Enthusiast thebasti's Avatar
    Join Date
    Aug 2004
    Location
    Novi Sad, Serbia
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Problem is that it won't work with yield either, i.e. you are probably getting a syntax error. Yield is used to execute a code block within a method that has been passed to it by caller. For example:

    Code Ruby:
    def foo
      # execute passed call block giving it a string as a param
      yield 'hello'
    end
     
    # call method passing it a block with print statement
    foo {|x| print x }

    This will output 'hello'. It's a stupid example but illustrates the point.

    When you replace yield with while it prints only 1 because in the first loop it will call return, which will effectively exit from the FibUpTo method and return a value - the rest of the loop is not executed at all.

    You might want to take a look at this and analyze how they did it: http://langexplr.blogspot.com/2007/0...statement.html
    "Strategy without tactics is the slowest route to victory.
    Tactics without strategy is the noise before defeat."
    - Sun Tzu
    Icebergist - a web dev blog | Orange Iceberg Web App Development

  3. #3
    SitePoint Member The_Big_K's Avatar
    Join Date
    May 2008
    Location
    In my home
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, great!

    Thanks a ton, thebasti!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •