Is there a way to combine these 2 blocks of code to make it less redundant?
puts "first number?"
num1 = gets.chomp.to_i
until num1.is_a?(Integer)
puts "please enter an actual number"
num1 = Integer(gets.chomp) rescue nil
end
puts "second number?"
num2 = gets.chomp.to_i
until num2.is_a?(Integer)
puts "please enter an actual number"
num2 = Integer(gets.chomp) rescue nil
end
You could do that as follows.
The dialog in getting the value for
num1was as follows.The dialog in getting the value for
num2was as follows.See Kernel#Integer and Kernel#loop.
Kernel#Integerwas given the optional argumentexception: falsein Ruby v2.6.One advantage of using
loopis that it provides a degree of data encapsulation. Unlikewhileanduntil,looptakes a block, thereby keeping prying eyes away from the values of local variables defined within the block. I rarely use anything other thanloopfor looping.