How to do loop in ruby - ruby

I need help putting this question in a loop:
puts "Rate the requirements and quality on a scale from 1-10 points."
x = gets.chomp.to_f
raq = 3318.6 * 1.5066**x
puts "This will cost " + raq.to_s + "kr."
If the user answers anything other than 1 through 10, they must be asked the question again. I have many questions in a row, so I would appreciate not having the whole program restart but just the single question.

Something like this should work:
x = nil
until (1..10).include? x
puts "Rate the requirements and quality on a scale from 1-10 points."
x = gets.to_f
end
raq = 3318.6*1.5066**x
puts "This will cost #{raq}kr."
(Personally, I'd try to use something a little more descriptive than x :) )

Related

Using `while` to repeat the process if user wants to do another operation

I wrote the following code:
puts "Money to deposit:"
money_invested = gets.to_f
puts "Time in days:"
time_investment = gets.to_f
puts "Indicate interest rate:"
interest_rate = gets.to_f
investment_calculation =
money_invested * (1 + interest_rate / 100 * time_investment / 365)
puts "Your money will be: $%.2f." % investment_calculation
I want to ask if the user wants to perform another operation:
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
another.operation = gets.chomp
If the user says N, I would say something like puts "Thanks for your time! The app will be closed in one minute. But if the user wants to run another operation (type Y), I need to run all the code again. I know this can be done with while, but don't know exactly. Any ideas?
You can maintain an infinite loop, and break it when desired:
NO = %w{ n no nope negative negatory nyet }
loop do
# all of your various questions & responses
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
response = gets.chomp
break if NO.include?(response.downcase)
# Additional code could go here, if it's appropriate
# to perform repeated actions after user indicates
# they don't want to quit
end
# cleanup code here
Use a boolean variable to switch between true/false based on user input. The first run it will be implicitly true:
do_loop = true
while do_loop
puts "Money to deposit:"
money_invested = gets.to_f
puts "Time in days:"
time_investment = gets.to_f
puts "Indicate interest rate:"
interest_rate = gets.to_f
investment_calculation = money_invested * (1 + interest_rate/100 * time_investment/365)
puts "Your money will be: $%.2f." % investment_calculation
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
answer = gets.chomp
# assign "true" to loop variable only if first character is 'Y' or 'y'
do_loop = answer.size > 0 && answer.downcase[0] == 'y'
end

I don't understand what's wrong with this simple Ruby code

I wrote this program to ask users for their age, and then tell them how old they will be in 10-50 years. I don't understand what's wrong with it :( I'm just a beginner and any help would be greatly appreciated.
print "How old are you?"
age = gets.chomp
i = 1
while i < 6
multiple = i * 10 + age
puts "In #{multiple} years you will be #{multiple}"
i++
end
Many ways to accomplish what you're trying to do. Make sure you're indenting blocks correctly - it'll make your code much more readable. Note that to_i converts your input from a String to an Integer. Also, try to name your variables more specifically; multiple doesn't really mean anything in your example.
puts "How old are you?"
age = gets.chomp.to_i
(1..5).each do |i|
years_passed = i * 10
new_age = years_passed + age
puts "In #{years_passed} years you will be #{new_age}"
end
If you want to use a while loop, you could do:
puts "How old are you?"
age = gets.chomp.to_i
multiplier = 1
while multiplier <= 5
years_passed = multiplier * 10
new_age = years_passed + age
puts "In #{years_passed} years you will be #{new_age}"
multiplier += 1
end

Ruby programming double a penny a day for period of time

I am new, three wekks into Ruby as my first Language. here is the code I already have:
=begin
this program is to calculate doubling a penny a day for thirty one days
=end
puts "how many days would you like to calculate"
days = gets.chomp.to_i
i = 1
loop do
puts "#{i}"
break i >=100
end
I have tried to use ** as this is they syntax for exponential use. I have considered an until loop also, but the thing I am having most difficulty with is how to double per day each integer for given time.
I have also tried "#{i**2}" , "#{i**i}" , I have tried to google this problem for the past 2 days, to no avail.
It can be done using a simple bit shifting operation. Binary value "1" shifted left n times is used to calculate 2^n.
puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 1 << (days - 1)
You don't need any loop here. What about a power? If you want to double 1 penny in 31 days, you need to calculate 2^30:
puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 2 ** (days - 1)
Try:
# Display the question to the user in the terminal
puts 'How many days would you like to calculate?'
# Get the number of days from stdin
days = gets.chomp.to_i
# starting at 1 and up to the number of days start doubling. Reduce returns the result back to itself, thus doubling the return of each number until you have reached the up to limit.
result = 1.upto(days).reduce { |start| start * 2 }
# Put the result
puts result
31.times.reduce 1 do |a| a * 2 end
#=> 2147483648

rounding off to the nearest number ruby

def percent_more
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
end
Now that code will tell you what percent more biggest_number is than smallest_number. But the problem is it prints out a long list of decimals, which are a pain to sort through. So if I wanted the code to only show say the first 3 numbers what would I do??
What you want to use is total_percent_more.round like so:
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more.round}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
See the docs for more info :
http://www.ruby-doc.org/core-2.1.2/Float.html#method-i-round
in ruby versions earlier than 1.9 you'll need to use sprintf like so:
puts "Your biggest number is #{sprintf('%.2f', total_percent_more)}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
You can change the amount of decimal places by changing the number.
See docs for more details:
http://www.ruby-doc.org/core-1.8.7/Kernel.html#method-i-sprintf
result = 10/6.0
puts result
printf("%.3f\n", result)
--output:--
1.66666666666667
1.667
Here is an example how to round to 2 decimal places
amount = 342
puts amount.round(2)
If you wanted to round to the nearest 3 decimal places then something like:
puts amount.round(3)

Ruby gets/puts only for strings?

I'm new to Ruby and am currently working on some practice code which looks like the following:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.chomp
puts 'Your favourite number is ' + num + '?'
puts 'Well its not bad but ' + num * 10 + ' is literally 10 times better!'
This code however just puts ten copies of the num variable and doesn't actually multiply the number so I assume I need to make the 'num' variable an integer? I've had no success with this so can anyone show me where I'm going wrong please?
If you are using to_i, then chomp before that is redundant. So you can do:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts 'Your favourite number is ' + num.to_s + '?'
puts 'Well its not bad but ' + (num * 10).to_s + ' is literally 10 times better!'
But generally, using "#{}" is better since you do not have to care about to_s, and it runs faster, and is easier to see. The method String#+ is particularly very slow.
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts "Your favourite number is #{num}?"
puts "Well its not bad but #{num * 10} is literally 10 times better!"
Use the to_i method to convert it to an integer. In other words, change this:
num = gets.chomp
To this:
num = gets.chomp.to_i
you can also make sure the number that the user is using is an integer this way:
num = Integer(gets.chomp)
but you have to create a way to catch the error in case the user input otherwise like a char, or string so; it is must better to use:
num = gets.chomp.to_i
In case the user put another type of data, num will be equal to 0 like you can see in this test example:
puts "give me a number:"
num = gets.chomp.to_i
if num >3
puts "#{num} es mayor a 3 "
else
puts "#{num} es menor a 3 o 3"
end
This a example of the interaction with that script:
give me a number:
sggd
0 es menor a 3 o 3
nil
I hope this clarify better your point.
I wrote a similar program as yours. Here is how I finally got it to work properly! I had to assign the favorite number to be an integer. Then, in the next line I set the new_fav_num with the value of fav_num +1 and then converted it to string. After that, you can just plug your code into the return statement that you want to say to the user, only you have to convert the first fav_num to a string.
puts "What is your favorite number?"
fav_num = gets.chomp.to_i
new_fav_num = (fav_num + 1).to_s
puts "Your favorite number is " + fav_num.to_s + ". That's not bad, but " +
new_fav_num + " is bigger and better!"
Hope this helps.

Resources