Can I insert an `if` condition inside a `case` statement? [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 7 years ago.
Improve this question
I'm trying to build a game. I want to give the users options depending on what they choose. My code has to be in a case statement:
puts "HA! you are in Saw 18"
puts "Lets play a deadly game! >=D"
puts "Options: hight, Who is Superman, Bake a pie "
option = gets.chomp
case option
when "hight"
puts "Lets see your hight yo!"
option_1 = gets.chomp
case option_1
when
end
end
If they choose the Hight,
if i >= 5 ft
puts "you may live"
else
puts "you in trouble"
Any other alternatives using case are very welcome.

Yes, you can insert a condition inside the case statement.

You could call a function from the case statement and put the if condition inside the function. Unless you have a good reason not to do this?

Yes you can, I suppose (trying not to change your code too much) you could do something like this:
puts "HA! you are in Saw 18"
puts "Lets play a deadly game! >=D"
puts "Options are: height, Who is Superman or Bake a pie "
option = gets.chomp
case option
when "height"
puts "Lets see your height yo!"
option_1 = gets.chomp.to_i
if option_1 >= 5
puts "you may live"
else
puts "you're in trouble"
end
when "Who is Superman"
#code
else
#code
end

Related

Not getting expected answer [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 3 years ago.
Improve this question
Code not returning the correct answer.
I've tired assigning a value to the animal choices. I've put it in the def and outside of it.
puts "Choose your favorite: cats or dogs"
choose = gets
cats = 1
dogs = 2
def favorite_animal (number)
remainder_when_divided_by_2 = number % 2
if remainder_when_divided_by_2 == 0
return "Ken does too."
end
if remainder_when_divided_by_2 == 1
return "Dogs are better!"
end
end
If the user enters Cats the answer "Ken does too!" should show. If the user enters Dogs the answer "Dogs are better!" should show. All I've gotten is 1 or 2 as an answer.
Try this.
loop do
puts "Choose your favorite: cats or dogs"
case gets.chomp
when "cats"
break "Ken does too."
when "dogs"
break "Dogs are better!"
else
puts "That answer is invalid. Try again"
end
end
Here is an example of a session using this code, with my answers being "pigs" and "dogs".
Choose your favorite: cats or dogs
pigs
That answer is invalid. Try again
Choose your favorite: cats or dogs
dogs
#=> "Dogs are better!"
See Kernel#loop. Many Rubyists use loop with the keyword break for most loops, rather than while or until. (for loops are never used).
For what you are doing you don't need a method, but if you want one add the line
def favorite_animal
at the beginning and the line
end
at the end. Then
favorite_animal
#=> "Dogs are better!"
provided I were to give the same answers as I did earlier.
There's a couple things going on:
You have to call the method favorite_animal somewhere; you've only defined it
Your cats/dogs isn't "mapped" to anything, so you need some logic to convert your input into a number, before you call the favorite_animal method
You still have to do something with the value you return inside your method (puts or something else to get it to show)
Here's a minimum example that works that might be useful for you to see the 3 issues above
def favorite_animal (number)
remainder_when_divided_by_2 = number % 2
if remainder_when_divided_by_2 == 0
return "Ken does too."
end
if remainder_when_divided_by_2 == 1
return "Dogs are better!"
end
end
puts "Choose your favorite: cats or dogs"
choose = gets.chomp
answer = if choose == 'cats'
1
else
2
end
puts favorite_animal(answer)

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.

Resources