currency converter in ruby [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Been straggling for couple of hours with my work of creating a converter. it should convert from one currency to the other
this is the code:
def converter
puts "Enter the amount you wish to convert"
userAmount = gets
puts "Enter your choice: 1 for converting Qatari
Riyals to US Dollars"
puts "Enter your choice: 2 for converting USD ollars to Qatari Riyals"
choiceConvert = gets
while choiceConvert != 1 || choiceConvert != 2 do
puts "please enter either 1 or 2"
choiceConvertNew = gets
choiceConvert = choiceConvertNew
end
if choiceConvert == 1
convertedAmount = userAmount / 3.65
puts "Your choice is to convert #{userAmount} Qatari Riyals to US Dollars;
You get #{convertedAmount} US Dollars"
else
convertedAmount = userAmount * 3.65
puts "Your choice is to convert #{userAmount} US Dollars to Qatari Riyals;
You get #{convertedAmount} Qatari Riyals"
end
end
converter

You are trying to do to much in one place try this
def convert_currency(amount,choice)
converted_amount = choice == 1 ? amount / 3.65 : amount * 3.65
from, to = choice == 1 ? ["Qatari Riyals", "US Dollars"] : ["US Dollars","Qatari Riyals"]
puts "Your choice is to convert #{sprintf('%.2f',amount)} #{from} to #{to}; You get #{sprintf('%.2f',converted_amount)} #{to}"
end
puts "Please Enter an Amount"
user_amount = gets.to_f
choice_convert = nil
while ![1,2].include?(choice_convert)
puts "Enter your choice: 1 for converting Qatari Riyals to US Dollars"
puts "Enter your choice: 2 for converting US Dollars to Qatari Riyals"
choice_convert = gets.to_i
end
convert_currency(user_amount,choice_convert)

Related

How to solve ruby string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm new to ruby, and I'm trying to make a simple calculator in which a user types in a simple problem (such as addition or subtraction) and the answer is returned. The problem is when the user types in a question, the question itself is being returned instead of the answer to that question.
puts "How many Questions?"
questions = gets.chomp.to_i
questions.times do |problem|
puts "question: "
problem = gets.chomp
puts "answer: #{problem}"
end
Inside your loop, instead of:
problem = gets.chomp
puts "answer: #{problem}"
Try this:
problem = gets.chomp
solved_problem = eval(problem)
puts "answer : #{solved_problem}"
eval will take care of interpreting your string as a Ruby instruction. But it's very messy, because anyone could write any Ruby program in your input and eval will make it run, so it's not safe at all.
If you only want to take care of simple operations, you can use a regex first to check if the input string looks like what you want:
problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)
This will be true if the string starts with a number, followed by 0 to many spaces, followed by either a + or - sign, followed by 0 or more spaces, followed by another number and nothing else. Then you raise an error if this is not true.
Your loop now look like this:
questions.times do |problem|
puts "question: "
problem = gets.chomp
problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)
if problem_is_ok
puts "answer: #{eval(problem)}"
else
#I raise an error, but you might aswell just print it instead for your simple program
raise ArgumentError("Can't compute this")
end
end
Add and subtract can be simple ruby definitions
We pass in 5 and 1
The lower portion of the code is the clear user interface implementation
when we loop we do it 3 times
It outputs 3 options for the user to select from
We read in with chomp, standard in, the keyboard, chooses 1, 2, or 3
If elsif statements conditionally select for each case
Using string interpolation we render the variables a and b into a new string,
and run their respective methods (add or subtract)
Converting that methods integer output to a string, and concatenate it.
Outputting that to the users screen
The 3rd option does no calculation,
instead it prints to users screen a simple string
our else condition catches the case when people don't enter one of the choices of 1, 2 or 3
It tells you to correct your choice to the options provided
Hope this helps
#!/usr/bin/env ruby
questions = 3
a, b = 5, 1
def add(a,b)
a + b
end
def subtract(a,b)
a - b
end
questions.times do |questions|
puts "Please choose:
1. add
2. subtract
3. exit"
questions = gets.chomp
if questions == '1'
puts "#{a} + #{b} = " + add(a,b).to_s
elsif questions == '2'
puts "#{a} - #{b} = " + subtract(a,b).to_s
elsif questions == '3'
puts 'exiting, goodbye.'
exit
else
p 'please choose again'
end
end

Ruby <, <=, >, >= value comparison code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The intent is to display message based on age.
puts "Age, please"
value = gets.chomp
if value < 21
puts "Here you cannot to buy alchohol"
end
puts "You can buy all the alchohol you want"
What is the missing part in this code?
if you get value by gets, value is String.
Use value.to_i
puts "Age, please"
value = gets
value = Integer(value) rescue 0
if value < 21
puts "Here you cannot to buy alchohol"
else
puts "You can buy all the alchohol you want"
end

Cannot get else condition to display [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am working through a codeacademy project and I cannot get a certain condition to display. Here is my code.
When I select add and choose a movie to add, I want it to let me know if the movie I input already exists in the hash. When I type in a movie that already exists in the hash, it asks me for the rating anyway. I believe I have the else statement in the right place, but it does not seem to be working.
Update: I changed these two lines of code (removing the .to_sym)
title = title
if movies[title].nil?
It does not allow me to enter duplicates.
Now when I choose "add" then try to add "Memento" I get the error message
"#{title} already exists. Its rating is #{rating}!" #{rating} produces an integer of 1 (which makes no sense since the integer value is 4).
movies = {
"Memento" => 4,
"Inception" => 3,
"The Prestige" => 2,
"Interstellar" => 1
}
puts "What would you like to do?"
choice = gets.chomp.downcase
case choice
# ADD
when "add"
puts "What would you like to add?"
title = gets.chomp
title = title
if movies[title].nil?
puts "What its rating? (enter 1-4)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been added with a rating of #{rating}"
else puts "#{title} already exists. Its rating is #{rating}!"
end
# UPDATE
when "update"
puts "Updated!"
# DISPLAY
when "display"
puts "Movies!"
# DELETE
when "delete"
puts "Deleted!"
# ERROR
else
puts "Error!"
end
When you removed the to_sym calls you didn't remove all of them:
movies[title.to_sym] = rating.to_i
and
Its rating is #{rating}!"
doesn't reference the movie rating it references the variable rating. Which hasn't been set yet.
the else block should be
rating = movies[title]
puts "#{title} already exists. Its rating is #{rating}!"
Since title is a string, you don't need to convert it to a symbol. And then you can use Hash::include? to see if the key exists.
# ADD
when "add"
puts "What would you like to add?"
title = gets.chomp
# title = title.to_sym # delete this line since the hash keys are strings
if !movies.include? title # use Hash::include? to see if key exists
puts "What its rating? (enter 1-4)"
rating = gets.chomp
...
else
puts "Movie already exists. Its rating is #{movies[title]}!" # remove .to_sym
end

Converting Strings to Symbols and Integers inside my hash in Ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I made it this far, but don't know where to add the .to_i and the .to_sym methods since I'm assuming I put them in the wrong place. Can someone help me out? When I test the code out it says "undefined method `to_sym=' for nil:NilClass"
movies = {
spiderman: 3,
superman: 4,
batman: 5
}
puts "what movie do you like?"
choice = gets.chomp
case choice
when 'add'
puts "What movie do you want to add?"
title.to_sym = gets.chomp
puts "what is the rating of that movie?"
rating.to_i = gets.chomp
movies[title]=rating
puts "Added!"
when 'update'
puts "What movie would you like to update?"
title = gets.chomp
puts "Updated!"
when 'display'
movies.each do |movies, ratings|
puts "#{movies}: #{ratings}"
end
puts "Movies!"
when 'delete'
puts "What movie would you like to delete from the list?"
title = gets.chomp
puts "Deleted!"
else
puts "Error!"
end
Besides []=, there is no method of the form foo=, or to_sym=, as in your code, in plain Ruby. If you want to get a user input as a symbol, you can do:
title = gets.chomp.to_sym
If you want to get an integer, you can do:
rating = gets.to_i
I don't know why you had chomp in the latter case.

if/else start the function again [closed]

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.

Resources