Ok i seriously suck at passing method to methods whenever i want to return something from the method. Can you guys explain on how do i go about passing it.
Here's my hash
$choosen_gun = {}
$Weapon = {
:Bazoka => ["Bazoka",5],
:Machine_gun => ["Machine_gun",1000],
:Hand_gun => ["Hand_gun",24,2],
:Double_Hand_gun => ["Double_Hand_gun",24,4],
:Sniper => ["Sniper",12,1],
:Shot_gun => ["Shot_gun",8,2]
}
Here's my code for method Weapon
def Weapon
puts "Now it's time to select your weapon."
puts "Please choose a weapon that is good throughout the game."
puts "Whenever you are shortage of bullets, please reload it."
puts "Please avoid last minute of reloading of weapon."
puts "Now choose your weapon based on your own preferences."
print "\n"
puts "Type 1"
puts "Gun Name: Bazoka"
puts "Description: A powerful gun that is strong with only 5 bullets."
puts "Rating: ★ ★ ★ ★"
num = gets.chomp.to_i
case num
when 1
puts "Selection of Bazoka is chosen"
puts "Loaded 5 bullets only"
$choosen_gun[num] = $Weapon[:Bazoka]
end
return num
end
Upon calling the method. The user will choose his weapon and it will add it to the $choosen_gun hash with it's num, and it's return it's num what the user types
Here's my code for method ZombieRoom
def ZombieRoom(w)
zombie = {
:Construcied => [5],
:Invader => [5],
:Damned => [5],
:Steampunk => [5],
:Stoner => [5],
:Wasted => [5],
:Romero => [5]
}
puts "Welcome to the worst night mare of Zombie Room"
puts "You will be fighting with a random zombie"
while true
puts ".........."
puts "Selecting a random zombie"
puts "Selecting your prefered gun...."
case w
when 1
$choosen_gun[1]
puts "Your selected gun is #{$choosen_gun[1][0]}"
#values = zombie.values
#puts values[rand(values.size)]
#random_zombie = zombie.keys.sample(1)
#puts random_zombie[
random_zombie = zombie.to_a.sample(1).to_h
random_zombie.each do |key,value|
puts "Your random zombie is #{key}"
puts "With a health value of #{value[0]}"
puts "Time to take down that zombie now."
while true
puts "Type Shoot to knock it down or quit."
choice = gets.chomp
if $choosen_gun[1][1] >= 1
health = value[0] -= 1
$choosen_gun[1][1] -= 1
puts "#{key} health now is #{health}"
else
puts "Please reload your gun"
puts "Reloading......"
$choosen_gun[1][1] += 5
end
if health == 0
puts "You have defeated #{key}"
puts "Congrats!!!"
puts "We are happy for you"
puts "Lets begins to collect your prize"
CollectPrize()
else
puts "You did not defeat the #{key} yet"
end
end
end
end
end
end
Here's my code for method CollectPrize
def CollectPrize
puts "Congratulations on defeating"
puts "We would now like to give you some case prizes"
print "\n"
puts "Please choose only 1 prize for yourself"
print "\n"
puts "Type 1"
puts "$50,000"
print "\n"
puts "Type 2"
puts "$25,000"
print "\n"
puts "Type 3"
puts "$55,000"
hoho = gets.chomp.to_f
if hoho == 1
puts "hehe"
end
end
Here how i call my method
ZombieRoom(Weapon())
CollectPrize()
Now the problem is that whenever the CollectPrize method is called and i type my input to collect the prize example 1 then it print "$50,000". instead of the ending the problem, it went back to the ZombieRoom and continues to loop at the "Type Shoot to knock it down or quit." Can someone atleast tell me a proper way to solve this issue or also what other way to pass a method?
Your code is in a large while true loop. Since true is always true, it will never end, so after it calls CollectPrize() it just goes back to the while statement.
You could get out of it by inserting a break line after the CollectPrize() but there's another while true loop around this one.
I think you need to pay closer attention to how you want to exit the while loops.
puts "Time to take down that zombie now."
while true # <---------------- this is ALWAYS going to loop, without end
puts "Type Shoot to knock it down or quit."
choice = gets.chomp
if $choosen_gun[1][1] >= 1
health = value[0] -= 1
$choosen_gun[1][1] -= 1
puts "#{key} health now is #{health}"
else
puts "Please reload your gun"
puts "Reloading......"
$choosen_gun[1][1] += 5
end
if health == 0
puts "You have defeated #{key}"
puts "Congrats!!!"
puts "We are happy for you"
puts "Lets begins to collect your prize"
CollectPrize()
else
puts "You did not defeat the #{key} yet"
end
end
In ruby constants start with Capital letter.
Methods are always defined in lower case.
Try this in irb
irb(main):001:0> def Weapon
irb(main):002:1> end
=> :Weapon
irb(main):003:0> Weapon
NameError: uninitialized constant Weapon
To solve your problem name methods using ruby's naming conventions:
zombie_room, collect_prize etc.
Then this code will work:
zombie_room(weapon())
What you are doing there is not really passing method weapon to method zombie room.
What is really going on is that method weapon is executed, then it returns a value and result of that value is passed to method zombie_room.
I think that is what you wanted.
If you need to pass a method, check out documentation for proc and lambda or just use blocks.
Related
I wrote a program that would see if you are on a party list. It works fine, but I wan't to add something so you can choose how many people are in your party compared to the default of five in this one. Thanks, any help would be appreciated. I just started so sorry if I don't understand.
puts "Create a party"
puts "Who is the first person: "
first_person = gets.chomp.upcase()
puts "Who is the second person: "
second_person = gets.chomp.upcase()
puts "Who is the third person: "
third_person = gets.chomp.upcase()
puts "Who is the fourth person: "
fourth_person = gets.chomp.upcase()
puts "Who is the fifth person: "
fifth_person = gets.chomp.upcase()
friends_list = Array[first_person, second_person, third_person, fourth_person, fifth_person]
puts "What is your name?"
your_name = gets.chomp.upcase()
if friends_list.include? your_name
puts "Congrats, you were invited"
else
puts "Sorry, you weren't invited. Please check with the host of the party for more details"
end
This is an example grouping instructions in methods so you can reuse some (see get_name), to be DRY.
Also, it uses a hash to store person details into the array.
The program keeps running in loop to until it breaks by user input.
def run
people = []
loop do
show_options
answer = gets.chomp.downcase.to_sym
case answer
when :a
add_person_to people
when :l
list people
when :f
find_in people
else
break
end
end
end
def show_options
puts "-"*50
puts "A: add person"
puts "L: list people"
puts "F: find person"
puts "any other key: exit"
end
def get_name
puts "Name?"
name = gets.chomp.capitalize
puts "Nickname?"
nickname = gets.chomp.capitalize
{name: name, nickname: nickname}
end
def add_person_to people
puts "Adding person nr. #{people.size + 1}"
people << get_name # check if already present?
end
def list people
puts "-"*50
people.each { |person| puts "Name: #{person[:name]} - Nickname: #{person[:nickname]}" }
puts "Total people: #{people.size}"
end
def find_in people
puts people.include? get_name # or improve
end
run # this calls the run method
That's great you've started to learn Ruby!
You can use loop. Make an array first and push the names into it.
puts "Create a party"
puts "Enter blank if you are done"
friends_list = [] # new array
count = 1
loop do
print count.to_s + "th person's name: "
name = gets.chomp.upcase
break if name.empty?
friends_list.push(name) # add person to list
count += 1
end
puts "What is your name?"
your_name = gets.chomp.upcase()
if friends_list.include? your_name
puts "Congrats, you were invited"
else
puts "Sorry, you weren't invited. Please check with the host of the party for more details"
end
Hey the code I created only repeats 2 times.
After I type the second time "y" for the "continue_question"-method the code only stops.
def greeting
puts "Hello! Please type your name: "
name = gets.chomp.capitalize
puts "It is nice to meet you #{name}. I am a simple calculator application."
puts "I can add, subtract, multiply, and divide."
end
greeting
def calculator
puts "First number: "
#n1 = gets.chomp.to_i
puts "Secons number: "
#n2 = gets.chomp.to_i
def calculation
puts "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: "
operation_selection = gets.chomp.to_i
if operation_selection == 1
#result = #n1 + #n2
elsif operation_selection == 2
#result = #n1 - #n2
elsif operation_selection == 3
#result = #n1 * #n2
elsif operation_selection == 4
#result = #n1 / #n2
else
puts "Something went wrong!"
calculation
end
end
calculation
puts "Your Result is #{#result}"
end
calculator
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
continue_question
Your code does not repeat 2 times, it repeats once.
The reason is because in your continue_question method, you do not tell it to repeat again:
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator # <-- This causes it it repeat ONCE!
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
A quick fix is to re-call the continue_question method below that line, to recursively repeat itself:
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
continue_question # <-- Add this to repeat indefinitely
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
The problem is that continue_question only executes once, at the end of your code, but you need to loop until user exits (i.e types n).
So simply add a loop inside continue_question, for example:
def continue_question
continue = "y"
until continue == "n" do
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
else
puts "What?"
end
end
end
Hey the code I created only repeats 2 times.
I think you misunderstand the following:
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
When you call the above function calculator, you are still executing the continue_question function. So when the calculator finishes executing, continue_question will finish as well and the program will stop. For the wanted result you can try using a loop.
How do I get the .include? to work? When the user chooses a character, I want the console to print the puts ok statement and then go to the if statement.
name = {"1" => "Mario",
"2" => "Luigi",
"3" => "Kirby",
}
puts "Peach's apocalypse, will you survive?"
def character (prompt, options)
puts = "who will you be?"
options = name[1] || name[2] || name[3]
character = gets.chomp.downcase
until character.include? name
end
puts "ok #{name} all three of you run out of peach's castle which has been overrun"
if character = name[1] || name[2] || name[3]
puts ("zombies are in the castle grounds, there are weapons over the bridge")
puts "What do you do, charge through or sneak?"
x = gets.chomp.downcase
if x == "sneak"
puts "oh you died"
if x == "charge through"
puts "the zombies tumbled over the bridge's edge, you made it safe and sound"
else
puts "you did nothing and were eaten alive by Princess Peach"
end
end
end
end
It looks like you're calling include? on a string. This will only return true if you pass it a substring of itself. For example:
"Mario".include?("Mar") #=> true
You want to call include? on the array of keys in the name hash. You could do:
name.values.include?(character)
or more concisely
name.has_value?(character)
Here's some documentation on the include? method of the Array class and the include? method of the string class, as well as the has_value? method of the Hash class.
There's considerably more that needs modifying for this program to run as you're expecting it to though. Here's one working implementation:
puts "Peach's apocalypse, will you survive?"
names = {
"1" => "Mario",
"2" => "Luigi",
"3" => "Kirby"
}
def choose_character(character = "", options)
puts = "who will you be?"
options.each do |num, name|
puts "#{num}: #{name}"
end
until options.has_key? character or options.has_value? character
character = gets.chomp.capitalize
end
return options[character] || character
end
name = choose_character(names)
puts "ok #{name} all three of you run out of peach's castle which has been overrun"
puts "zombies are in the castle grounds, there are weapons over the bridge"
puts "What do you do, charge through or sneak?"
case gets.chomp.downcase
when "sneak"
puts "oh you died"
when "charge through"
puts "the zombies tumbled over the bridge's edge, you made it safe and sound"
else
puts "you did nothing and were eaten alive by Princess Peach"
end
The answer above is great and features awesome refactoring, but I would use
character = gets.strip.downcase
instead as it also gets rid of any potential whitespace.
To elaborate on the string thing, 'gets' stands for 'get string' (or at least so I was taught), so everything you get via 'gets' will be a string until you convert it further. Consider this:
2.2.1 :001 > puts "put in your input"
put in your input
=> nil
2.2.1 :002 > input = gets.strip
5
=> "5"
2.2.1 :003 > input.class
=> String
You would have to use .to_i to convert your input back to integer.
I'm doing a game creation exercise from Learn Ruby the Hard Way. It's themed after Destiny since that's what I've got on the brain at the moment.
I wanted to have the player pick a character class, and then have that choice hand off some numbers as stats to be checked later in play. Below is the version that actually worked, but it involves creating a several global variables, which I keep reading is not a "best practice" in Ruby.
My question is, is there a way to do what I've got the code below doing without creating all of these global variables, or am I doing what needs to be done?
$might = 1
$agility = 1
$intellect = 1
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
if choice == "1"
$might = 3
puts "You've chosen Titan!"
elsif choice == "2"
$agility = 3
puts "You've chosen Hunter!"
elsif choice == "3"
$intellect = 3
puts "You've chosen Warlock!"
else
puts "Try again."
start
end
end
puts start
puts "Might: #{$might}"
puts "Agility: #{$agility}"
puts "Intellect: #{$intellect}"
You can create a class and use instance variables:
class Game
def initialize
#might = 1
#agility = 1
#intellect = 1
end
attr_reader :might
attr_reader :agility
attr_reader :intellect
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
case choice
when "1"
#might = 3
puts "You've chosen Titan!"
when "2"
#agility = 3
puts "You've chosen Hunter!"
when "3"
#intellect = 3
puts "You've chosen Warlock!"
else
puts "Try again."
start
end
end
end
game = Game.new
game.start
puts "Might: #{game.might}"
puts "Agility: #{game.agility}"
puts "Intellect: #{game.intellect}"
Remark:
I replaced your if-sequence with a case-statement
attr_reader defined the attribute accessor for the instance variables.
Maybe something like this. I prepare it for updates.
class Character
attr_accessor :might, :agility, :intelect, :type
def initialize(type, might = 1, agility = 1, intelect = 1)
#type = type
#might, #agility, #intelect = might, agility, intelect
end
def print_attributes
puts "Type: #{#type}"
puts "Might: #{#might}"
puts "Agility: #{#agility}"
puts "Intelect: #{#intelect}"
end
end
class Player
attr_reader :character
def initialize(character)
#character = character
end
end
class Game
CHARACTER_CLASSES = [
{:type => "Titan", :might => 3, :agility => 1, :intelect => 1},
{:type => "Hunter", :might => 1, :agility => 3, :intelect => 1},
{:type => "Warlock", :might => 1, :agility => 1, :intelect => 3}
]
attr_reader :player
def initialize
#player = nil
end
def start
puts "Make all decisions by pressing the corresponding number."
repeat = true
while repeat
puts "Choose your class:"
CHARACTER_CLASSES.each_with_index do |char_config, i|
puts "#{i+1}. #{char_config[:type]}"
end
choice = gets.chomp
choice_i = choice.to_i
unless choice_i == 0
if char_data = CHARACTER_CLASSES[choice_i - 1]
#player = Player.new( Character.new(char_data[:type], char_data[:might], char_data[:agility], char_data[:intelect]) )
repeat = false
end
end
end
end
end
game = Game.new
game.start
game.player.character.print_attributes
One option could be returning whatever you want from a method:
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
case choice
when '1'
puts "You've chosen Titan!"
{agility: 1, might: 3, intellect: 1}
when '2'
puts "You've chosen Hunter!"
{agility: 3, might: 1, intellect: 1}
when '3'
puts "You've chosen Warlock!"
{agility: 1, might: 1, intellect: 3}
else
puts "Try again."
start
end
end
hero = start
puts "Might: #{hero[:might]}"
puts "Agility: #{hero[:agility]}"
puts "Intellect: #{hero[:intellect]}"
def cafeteria
puts "The cafeteria is a mess, as you walk into the kitchen all the pots and pans are all over the floor."
puts " The freever is open, everything has spoiled, and it smells awful!"
puts "At the far end of the kitchen a set of knives is lying on the floor."
puts "What do you do?"
prompt()
action = gets.chomp
if action.include? 'knife' or 'knives'
puts "Yes! now you have a weapon."
puts "Now what?"
elsif action == "leave."
return :hallway
else
puts "I don't understand."
return :death
end
end
action.include? 'knife' or 'knives' will always yield truth value. (even though there's no kinfe, knives in the string)
action = 'asdf'
# => "asdf"
action.include? 'knife' or 'knives'
# => "knives"
because it is interpreted as (action.include? 'knife') or 'knives'
Maybe you mean following?
action.include? 'knife' or action.include? 'knives'
# => false