From: Dan Nachbar Date: 2011-10-22T20:57:28+09:00 Subject: Re: power of 2 code On Oct 22, 2011, at 12:37 AM, Ray DarkScythe wrote: > hello I am new here and new to ruby (no programming experience but > willing to learn) > > I am following "Daniel Carrera" tutorial I am already at while loops and > fairly I understand of it but the one thats bugging me is the exercise > of the power of 2. ... I would make three changes to your code. First, in your code you have a variable named "number". Actually, there are a pair of numbers. I think one reason you are having trouble is that you have confused yourself about what "number" is supposed to be doing. So I suggest that you use more descriptive variable names such as (for this example) "limit" and "exponent". Secondly, I'd do the exponentiation explicitly rather than implicitly the way your code does. The third problem you are having is a classic "off by one" error. You test ever-increasing values until one is too big. You then print out the excessively large value. But the desired result is last value that is not too big. In other words, you report a value that has been increased one too many times. (Off-by-one errors are extremely common when looping.) So, using more descriptive variable names, explicit exponentiation, and reworking the while loop to "test ahead" to avoid the "off by one" problem: puts "Enter a maximum value: " limit = gets.chomp.to_i exponent = 0 while (2 ** (exponent+1)) < limit exponent += 1 end puts exponent.to_s + " is the highest " + \ "power of 2 less than " + limit.to_s That's actually a tricky bit of coding. I have to admit that I initially tripped over the off-by-one issue while giving it a try. So don't be surprised that it gave you some trouble. Have fun and keep plugging away. PS - You may have noticed that Ruby programmers often use very short variable names. So, for the above, some might use "l" and "e". This tendency is largely bravado. I suggest you stick with longer variable names while learning. You can save the keystrokes when you are more experienced and want to show off your refined poetic sensibilities. Dan Nachbar