New user - very basic question

A

Ashley Wharton

[Note: parts of this message were removed to make it a legal post.]

Hi - sorry to bother with such a basic question, but is there a better way
to write the following: (before I move on I want to make sure I am following
best practice)

def require_number number_cur
puts number_cur
reply = gets.to_i

while reply < 100
reply = reply + 1
puts reply
end

if reply > 100
true
require_number 'Please enter a number less than 100: '
end
end
require_number 'Enter a number: '

Thanks so much!
 
B

Benjamin Stiglitz

Not elegant, but better:

def require_number(prompt, max)
print prompt
reply = gets.to_i
if reply >= max then reply = require_number "Please enter a number
less than #{max}: ", max end
reply
end

require_number 'Please enter a number: ', 100
 
A

Ashley Wharton

[Note: parts of this message were removed to make it a legal post.]

Not elegant, but better:

def require_number(prompt, max)
print prompt
reply = gets.to_i
if reply >= max then reply = require_number "Please enter a number
less than #{max}: ", max end
reply
end

require_number 'Please enter a number: ', 100


Thank you for taking the time - could I trouble you further? If I want
the "reply" to iterate through until it reaches 100 could just add the
"while" to your code as below?

def require_number(prompt, max)
print prompt
reply = gets.to_i
if reply >= max then reply = require_number "Please enter a number
less than #{max}: ", max end
while reply < max
reply = reply + 1
puts reply
end
end
require_number 'Please enter a number: ', 100
 
B

Benjamin Stiglitz

Thank you for taking the time - could I trouble you further? If I want
the "reply" to iterate through until it reaches 100 could just add the
"while" to your code as below?
while reply < max
reply = reply + 1
puts reply
end

Even better is
reply.upto(max - 1) { |x| puts x }

-Ben
 
A

Ashley Wharton

[Note: parts of this message were removed to make it a legal post.]

Thank you very much! Take care,

ashley
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top