How can I change a function argument into a variable? - ruby

Here is my code currently:
def name_grabber(name)
puts "What is your #{name} name?"
print "> "
$name = gets.chomp
print $name
end
name_grabber("first")
name_grabber("middle")
name_grabber("last")
puts "Nice to meet you, #{first} #{middle} #{last}"
puts
I want it so I can but first as a string into name_grabber and then first become a variable I can use later.
Using Ruby 2.0.0

I think this is what you want:
def name_grabber(name)
puts "What is your #{name} name?"
print "> "
gets.chomp
end
first = name_grabber("first")
middle = name_grabber("middle")
last = name_grabber("last")
puts "Nice to meet you, #{first} #{middle} #{last}"
puts

Related

How to sum variables values RUBY

First, I am new to ruby so please be gentle hehe.
I have a school project where the assignment is to calculate the total cost of a project. In my code, the user is giving the variables some input. Later on, I want to show the total of all these inputs. (the inputs is number)
So basically I need to add them up and it needs to give me a sum of them.
How do I do that?
Hope you amazing people can help me:)
Here is my code:
file = File.new("testing.txt", "a")
class Project
def call_acc
prompt = "> "
puts
puts "What is the salary for an accountant?"
print prompt
while #accountant = gets.chomp
if !/\A\d+\z/.match(#accountant)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_dev
prompt = "> "
puts
puts "What is the salary for an developer?"
print prompt
while #developer = gets.chomp
if !/\A\d+\z/.match(#developer)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_mana
prompt = "> "
puts
puts "What is the salary for the top management?"
print prompt
while #management = gets.chomp
if !/\A\d+\z/.match(#management)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_office
prompt = "> "
puts
puts "What is the total office rent for the project?"
print prompt
while #office = gets.chomp
if !/\A\d+\z/.match(#office)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_lunch
prompt = "> "
puts
puts "What is the daily cost for lunch per person?"
print prompt
while #lunch = gets.chomp
if !/\A\d+\z/.match(#lunch)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_utilites
prompt = "> "
puts
puts "What is the total cost for utilites (internet, subscriptions etc)?"
print prompt
while #utilites = gets.chomp
if !/\A\d+\z/.match(#utilites)
puts
puts "Error: Only use numbers, please try again"
print prompt
else
break
end
end
end
def call_show
prompt = "> "
puts "____________________________________"
puts
puts "Is this information correct?"
puts
puts "Accountant salary (per hour): #{#accountant}kr\nDevelepor salary (per hour): #{#developer}kr\nTop management salary (per hour): #{#management}kr"
puts
puts "Total rent cost of office space: #{#office}kr\nLunch per person per day: #{#lunch}kr\nTotal cost of utilites #{#utilites}kr"
puts
puts "____________________________________"
puts "Yes or No"
print prompt
while user_imput = gets.chomp.upcase
case user_imput
when "YES"
file = File.new("testing.txt", "a")
file.puts("Account salary: #{#accountant}kr\nDeveloper selary: #{#developer}kr\nTop management salary #{#management}kr\nTotal rent cost: #{#office}kr\nLunch per person #{#lunch}kr\nUtilites cost #{#utilites}kr")
file.close
puts
puts "The information has now been stored"
puts "____________________________________"
break
when "NO"
puts
puts "The information has not been stored. Exiting application"
puts "____________________________________"
abort
else
puts
puts "Please either write Yes or No"
print prompt
end
end
end
def call_total
prompt = "> "
puts
puts "________Your information_______"
puts
puts "Accountant salary (per hour): #{#accountant}kr\nDevelepor salary (per hour): #{#developer}kr\nTop management salary (per hour): #{#management}kr"
puts
puts "Total rent cost of office space: #{#office}kr\nLunch per person per day: #{#lunch}kr\nTotal cost of utilites #{#utilites}kr"
puts
puts "________Total cost of project________"
puts
puts ?????????#accountant + #developer??????????????+
puts
end
project = Project.new
require 'io/console'
select = 0
prompt = "> "
puts
puts
puts "Welcome to KEA"
puts "____________________________________"
loop do(select != 7)
puts
puts "Press 1 to calculate"
puts "____________________________________"
select = STDIN.getch.to_i
if (select == 1)
project.call_acc
project.call_dev
project.call_mana
project.call_office
project.call_lunch
project.call_utilites
project.call_show
project.call_total
break
else
puts
puts "Invalid input. Please try again"
puts "____________________________________"
end
end
end
Answering the question stated in title:
numbers =
loop.inject([]) do |acc, _|
val = gets.to_i
break acc unless val > 0
acc << val
end
numbers.reduce(:+)

how to save changes made in my .rb program in the terminal?

I'm really new to this but I’ve written a small program that will CRUD a movie to a list the only problem is it is not saving the changes made. how can I make this happen?
error = "movie not found"
movies = {
Mazerunner: 1
}
error = "movie not found"
puts "welcome to CrudMovies"
puts "enter a command"
puts "type add to add a movie to the list"
choice = gets.chomp.downcase
case choice
when "add"
puts "what movie would you like to add"
title = gets.chomp
if movies[title.to_sym].nil?
puts "what would you like the rating of #{rating} (1-4)to be?"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} was added with a rating of #{rating}"
else
puts "that movie already exists"
end
when "update"
puts "what movie would you like to update? (case sensitive)"
title = gets.chomp
if movies[title.to_sym].nil?
puts "#{error}"
else
puts "what is the movie rating would you like to update?"
movies[title.to symb] = rating.to_i
puts "#{title}'s rating has been updated to #{rating}"
end
when "display"
movies.each do |x, y|
puts "#{x} Rating:#{y}"
end
when "destroy"
puts "what movie would you like to erase?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "#{error}"
else
movies.delete(title.to_sym)
puts "the movie no longer exists"
end
else
puts "command not recognized"
end
I'm going to assume that by "Save" you mean stored in the movies hash. The answer to that is that is it is in fact being stored. Only your script exits after you perform an operation, so you never get to see the updated movies.
To see the desired result you're going to want to wrap the majority of this in an infinite loop to prevent the script from naturally exiting.
Consider the following as an example:
store = []
while true
puts "Enter something:"
choice = gets.chomp
store.push choice
puts "Your choices so far are: #{store.inspect}"
end

Ruby if statements 3 conditions

puts 'guess my favorite num'
x = gets.chomp
unless x.kind_of?(Fixnum)
puts "it's not a Numeric symbol"
if x=="2"
puts "Well done!"
if x!=2 || x.is_a?(Fixnum)
puts "Try more, dude"
end
end
end
Trying to learn ruby, but my code is not work :-( Need 3 DIFFERENT conditions for var. Where is a bug ?
Consider this:
#!/usr/bin/env ruby
puts "Guess my favorite num."
x = gets.chomp
begin
if Integer(x) == 2
puts "Well done!"
else
puts "Try more, dude."
end
rescue ArgumentError
puts "It's not an integer."
end
Semi-contrived example, but you're probably looking for elsif:
puts 'enter a favorite num'
x = gets.chomp.to_i
if x == 2
puts "you entered 2"
elsif x !=2
puts "you did not enter 2"
end
Also--as #Jan Dvorak points out--the gets method returns a string, which you would want to convert (to integer in this case).
Another solution would be to use a case statement:
print 'enter a favorite num'
x = gets.chomp.to_i
case x
when 2
puts "you entered 2"
else
puts "you did not enter 2"
end
You did probably mean something like that:
loop do
puts 'guess my favorite num'
x = gets.chomp
case x
when /\D/
puts "it's not a Numeric symbol"
when "2"
puts "Well done!"
break
else
puts "Try more, dude"
end
end

Is there a "while...else" in Ruby?

I have a hash with cat names for keys and cat instances for values. Is there a way to make it so that when people type a response that isn't in a key in the cats hash for the terminal to reprint the puts "Which cat would you like to know about?" question or type: "Try again"? I guess I'm asking for sort of a "while... else".
puts "Which cat would you like to know about?"
puts cats.keys
response = gets.chomp
while cats.include?(response)
puts "The cat you chose is #{cats[response].age} old"
puts "The cat you chose is named #{cats[response].name}"
puts "The cat you chose is a #{cats[response].breed} cat"
puts "Is there another cat would you like to know about?"
response = gets.chomp
end
There isn't a "while...else", as far as I know. If you do not mind the loop continuing regardless of whether the response is a valid cat name or not, maybe this will work for you:
puts "Which cat would you like to know about?"
puts cats.keys
while true
response = gets.chomp
if response.empty?
break
elsif cats.include?(response)
puts "The cat you chose is #{cats[response].age} old"
puts "The cat you chose is named #{cats[response].name}"
puts "The cat you chose is a #{cats[response].breed} cat"
puts "Is there another cat would you like to know about?"
else
puts "There is no cat with that name. Try again."
end
end
This will repeatedly prompt the user for a cat name, until the user responds with an empty string, at which point it will break out of the loop.
You could rearrange your code with an additional question:
cats = {'a' => 1} #testdata
continue = true #set a flag
while continue
puts "Which cat would you like to know about?"
response = gets.chomp
while cats.include?(response)
puts cats[response]
puts "Is there another cat would you like to know about?"
response = gets.chomp
end
puts "Try another? (Y for yes)"
continue = gets.chomp =~ /[YyJj]/ #Test for Yes or yes, J for German J...
end
It has been a while since I have played with Ruby, but something like this comes to mind:
def main
print_header
while true
resp = get_response
if cats.include?(resp)
print_info(resp)
else
print_header
end
end
def get_response
puts cats.keys
response = gets.chomp
end
def print_header
puts "Which cat would you like to know about?"
end
def print_info response
puts "The cat you chose is #{cats[response].age} old"
puts "The cat you chose is named #{cats[response].name}"
puts "The cat you chose is a #{cats[response].breed} cat"
puts "Is there another cat would you like to know about?"
end
Please note that you will need a terminal point. If get_response returns "no", then quit.
continuous = false
loop do
unless continuous
puts "Which cat would you like to know about?", cats.keys
else
puts "Is there another cat would you like to know about?"
end
if cat = cats[gets.chomp]
puts "The cat you chose is #{cat.age} old"
puts "The cat you chose is named #{cat.name}"
puts "The cat you chose is a #{cat.breed} cat"
continuous = true
else
continuous = false
end
end

Ending while loops in one method from another method in Ruby?

I'm working on a simple text-based dungeon game in Ruby, and I've run into a snag. Basically, I have one room with a locked door. The key is found in another room and I want the door to be unlocked once the key has been found.
Here's what I've got so far:
def chest_room
puts "You are in a small, round room."
puts "On the floor in front of you is a small wooden chest."
puts "It does not appear to be locked."
puts "What do you do?"
chest_open = false
while true
prompt; next_move = gets.chomp
if next_move == "open chest"
chest_open = true
puts "Inside the chest, you see a small, brass key."
puts "What do you do?"
prompt; next_move = gets.chomp
elsif next_move == "take key" and chest_open
key_present = true
puts "You take the key and slip it into a pocket."
puts "What do you do?"
prompt; next_move = gets.chomp
elsif next_move == "go back"
start()
else puts "I don't understand you."
puts "What do you do?"
prompt; next_move = gets.chomp
end
end
end
def start
puts "You find yourself in a dank room lit by torches."
puts "There are three doors leading out of here."
puts "What do you do?"
door_open = false
key_present = false
while true
prompt; next_move = gets.chomp
if next_move == "door 1"
chest_room()
elsif next_move == "door 2"
dais()
elsif next_move == "door 3" and not door_open
puts "This door is securely locked."
puts "You'll need to find some way of opening it before you can enter."
puts "What do you do?"
prompt; next_move = gets.chomp
elsif next_move == "door 3" and key_present
door_open = true
puts "The key you found fits easily into the lock."
puts "With a click, you unlock the door!"
orb_room()
else
puts "I don't understand you."
puts "What do you do?"
prompt; next_move = gets.chomp
end
end
end
Any input or advice? Essentially, I want to end the door_open = false loop once the key is found, but I can't figure out how to set door_open = true in the chest_room method then call it from the start method. Thanks!
What you really need is to back up and think out the design again. You have a Room, and it has a property "open" or "closed". You have a Key, and you need the key to change the state of that open/closed property.
Write out what you want to do, and think about how to model it as a Room and a Key, and you'll be on a better track.
(No, I don't want to give you the answer. Figuring it out is more important.)
You're having scope issues. make the door_open or key_present instance variables by putting an # in front of them. Then any method can access them. also case/when is cleaner than if elsif
while !#key_present # #key_present can be modified in another method
prompt; next_move = gets.chomp
case
when "door 1" == next_move then chest_room() # put constants first when comparing ==
when "door 2" == next_move then dais()
# more conditions
end
end

Resources