This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
At the else, where the user didn't input a 1 or 2, the script should start over again after displaying the error message. How can I do that?
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
input = gets
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
elseif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
end
You need to wrap the entire thing in a while loop and initialize the variable input to a value like nil.
The while loop's condition should check if the value is 1 or 2, and it will probably need to be converted to an integer with .to_i since gets will return a string.
# initialize to nil
input = nil
# Check if the current value (integer) is 1 or 2
while !([1,2].include?(input))
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
# Convert the string to an int after getting it as input
input = gets.to_i
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
# elsif here, not elseif!!
elsif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
end
end
In fact, rather than a while loop, using an until loop (which Ruby has unlike many other languages) is more readable when testing for a negative condition:
until [1,2].include?(input)
...
end
The [1,2].include?(input) is a slicker way of writing
if input == 1 || input == 2
... that is easily expanded for additional values in the array.
This is it using a function.
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
def convert
input = gets
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
elseif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
convert()
end
end
If input != (2 || 1) could work too.
Related
I'm sure it would be hard to find an easier question, but I'm a complete newbie. I have searched extensively and for some reason can't find the answer to this. Here's my code:
puts "Enter F for Fahrenheit and C for Celsius."
x = gets.chomp.downcase
def ftoc(fahrenheit)
(fahrenheit.to_f - 32.0) * (5.0 / 9.0)
end
if x == "f"
puts "Enter your temp:"
temp = gets.chomp.to_i
ftoc temp
elsif x == "c"
puts "Enter your temp:"
temp = gets.chomp.to_i
ctof temp
else
puts "That does not compute."
end
I'm just trying to get the returned result of the method into a variable so I can use it elsewhere....
Remember that calls like ctof temp just initiate a method and then, as you're not putting the result anywhere, discard it immediately.
To clean up this code let's organize it better:
# Temperature conversion method
def ftoc(fahrenheit)
(fahrenheit.to_f - 32.0) * (5.0 / 9.0)
end
# User input method
def temperature_prompt!
puts "Enter F for Fahrenheit and C for Celsius."
x = gets.chomp.downcase
case (x)
when "f"
puts "Enter your temp:"
temp = gets.chomp.to_i
ftoc temp
when "c"
puts "Enter your temp:"
temp = gets.chomp.to_i
ctof temp
else
puts "That does not compute."
end
end
Now you can make use of the fact that in Ruby things like if and case actually return values. In this case it's the value of the last thing to execute in each block, so that result isn't discarded, it's just passed along:
temp = temperature_prompt!
If you enter an invalid value you get the result of puts which is conveniently nil.
Here's something to consider: Ruby is very good at parsing arbitrary text if you can describe the patterns. Here's a simple input routine:
def temperature_prompt!
puts "Enter degrees (e.g. 8F, 2C)"
case (input = gets.chomp.downcase)
when /(\d+)f/
ftoc $1
when /(\d+)c/
ctof $1
else
puts "That does not compute."
end
end
You could add to those patterns to allow things like -2C and 3.4°F if you wanted.
I wrote the following code in Ruby for Celsius to Fahrenheit conversion. I keep getting error. I am sure that I am still not clear on the concept of methods and that's why I cant figure it out.
puts "Enter the Degree in c:"
c = gets.chomp
def celsius_fahrenheit (f)
return f = ( c * 9 / 5) + 32
end
answer = "The #{celsius_fahrenheit (f)} equivalent is"
puts answer
You have several problems:
convert c to Float
change signature of celsius_fahrenheit to use c as a parameter
don't do an assignment in the method's body
Here is the code:
def celsius_fahrenheit(c)
c * 9 / 5 + 32
end
puts 'Enter C:'
c = gets.to_f
puts celsius_fahrenheit(c)
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
So far I've got
puts "Enter a calculation: "
calc = gets.chomp
def add(a, b)
puts a + b
end
puts add(calc)
And now I'm ashamed to admit but I'm stumped, I've tried writing add methods etc... but I just can't seem to wrap my head around getting this to calculate and output the correct results.
To simplify this, how can I get the ability to add working?
I.E user enters calculation (2 integers), program adds the
calculation, program outputs results, program asks for another
calculation.
I think this kind of script is perfect for a case statement. Here's a first pass that works with binary operators:
#! /usr/bin/ruby
def calc
puts "Calculator 1.0 \nEnter 'q' to quit."
while true
print ">> "
str = gets.chomp.split(" ") # splits into array, rejects blanks
return if str[0] == 'q' # quit if first element is 'q'
operand1 = str[0].to_i
operand2 = str[2].to_i
operator = str[1].to_sym
case operator
when :+ then puts operand1 + operand2
when :- then puts operand1 - operand2
when :* then puts operand1 * operand2
when :/ then puts operand1 / operand2
when :% then puts operand1 % operand2
else
puts "invalid input"
end
end
end
if __FILE__ == $0 # if run as script, start calc: see http://j.mp/HOTGq8
calc
end
Then, at the command line:
$ ./calc.rb
Calculator 1.0
Enter 'q' to quit.
>> 55 / 5
11
>> 90 / 10
9
>> 5 * 3093
15465
Good luck!
These are great resources if you're just starting out: RubyMonk Codecademy
Just think of your problem one step at a time. You want the user to provide to integers. So start with a simple prompt, like you have already done:
puts "Enter your first value"
Now get the value from the user:
firstVal = gets.chomp
Now provide another prompt, and get a second value.
puts "Enter your second value"
secVal = gets.chomp
And output your results:
puts "#{firstVal} + #{secVal} = #{firstVal.to_i + secVal.to_i}"
Sometimes just writing it out plain and simple is the easiest first step. Now you can create an add function to do this more efficiently. Try it out, and see if you have any luck!
EDIT:
Also, I noticed your add function takes two parameters, but you are only passing it one.
In order to call a function with two parameters, you need two values to provide it with. For example:
x = 5
y = 2
def add(a, b)
return a + b
end
puts add(x, y)
I know this is a bit older post, but people do still find this answer and I want to add to what jkrmr said above.
The code jkrmr posted is great but does not handle floating point calculations and that was an easy fix so I added that functinoality. :-)
#! /usr/bin/ruby
def calc
puts "Calculator 1.1 \nEnter 'q' to quit."
while true
print ">> "
str = gets.chomp.split(" ") # splits into array, rejects blanks
return if str[0] == 'q' # quit if first element is 'q'
if str[0].include? "."
operand1 = str[0].to_f
else
operand1 = str[0].to_i
end
operator = str[1].to_sym
if str[2].include? "."
operand2 = str[2].to_f
else
operand2 = str[2].to_i
end
case operator
when :+ then puts operand1 + operand2
when :- then puts operand1 - operand2
when :* then puts operand1 * operand2
when :/ then puts operand1 / operand2
when :% then puts operand1 % operand2
else
puts "invalid input"
end
end
end
if __FILE__ == $0 # if run as script, start calc: see http://j.mp/HOTGq8
calc
end
Here's a quick little calculator I whipped up to help you get started:
#! /usr/bin/ruby
def add(a, b)
a + b
end
while(true) do
puts "Enter a calculation: "
# chomp off the \n at the end of the input
calc = gets.chomp
# quit if the user types exit
exit if calc.include?("exit")
# puts the result of the add function, taking input of calc "split" into two numbers
puts add(calc.split("").first.to_i, calc.split("").last.to_i)
# spacing
puts
end
To build on that. If you want to continue to recieve calculation requests you can put the process in a loop(among many solutions).
while true
puts 'Enter Val 1'
v1 = gets.chomp.to_i
puts 'Enter Val 2'
v2 = gets.chomp.to_i
puts "#{v1} + #{v2} = #{v1+v2} "
end
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.