On Thu, Feb 13, 2014 at 7:29 PM, Jaimin Pandya <lists / ruby-forum.com> wrote=
:
> Jes=FAs Gabriel y Gal=E1n wrote in post #1136295:
>> On Tue, Feb 11, 2014 at 11:20 AM, Jaimin Pandya <lists / ruby-forum.com>
>> wrote:
>>>
>>>         puts x
>>>         end
>>>        x =3D x + 1
>>>        end
>>>
>>> But this solution of program is wrong.
>>>
>>> So How to solve this program? Please help me on this.
>>
>> What you need to do is to change the 10 in your first program by a
>> number entered by the user. So look into Kernel#gets
>> (http://ruby-doc.org/core-2.1.0/Kernel.html#method-i-gets) and how to
>> convert what the user enters into a number String#to_i
>> (http://ruby-doc.org/core-2.1.0/String.html#method-i-to_i), and you
>> need a second variable to store this number and check x against it.
>>
>> Hope this gets you in the right direction,
>>
>> Jesus.
>
> I solved the program by following :
>
> x =3D 0
> y =3D gets(10)
> while x <=3D y.to_i
>   puts x
>   x =3D x + 1
>   end
>
> Is this program correct? Could you please tell me?

Well, as others have said, first is to check if the program actually
does what you want. It prints from 0 to the number you type, included.
Is this what you want?

Apart from that there are a couple of things that could be made
better, and also a completely different way of doing it, which would
be more rubyish:

- If you check http://ruby-doc.org/core-2.0.0/Kernel.html#method-i-gets
you'll see that passing an integer to gets means it will read at most
those many characters from the input. Is that what you wanted?

- You are calling to_i many times, every time you check the loop
condition. Better like this:

y =3D gets.to_i

- In Ruby, generally, internal iterators are preferred over external ones:

y =3D gets.to_i
1.upto(y) {|n| puts n}

You can do inside the block what you need with n.
Or if you only want to print it:

y =3D gets.to_i
puts *(1..y)

I really recommend you read a tutorial on Ruby, the Ruby Programming
Guide, Chris Pine's Learn to Program (http://pine.fm/LearnToProgram/)
or some other introduction to the language.

Hope this helps,

Jesus.