Having some trouble checking for multiple sets of values.
loop do
turns(player1,player2)
break puts "you win!" if #entries.values[0..2].all?{|move| move == "X"}
end
I wanted to use a multi-dimensional hash like this. Is my syntax wrong or is this just something you cannot do?
loop do
turns(player1,player2)
break puts "you win!" if #entries.values[[0..2][3..5]].all?{|move| move =="X"}
end
another problem is when values[0..2] are already equal to "x" the loop doesn't break until the next turn.
Here is the repl
https://repl.it/JrQe/57
Source code
#entries = {1=>" ", 2=>" ", 3=>" ", 4=>" ", 5=>" ", 6=>" ", 7=>" ", 8=>" ", 9=>" "}
puts "###########################################"
puts " tic-tac-toe"
puts "\t\t 1 | 2 | 3 "
puts "\t\t-----------"
puts "\t\t 4 | 5 | 6 "
puts "\t\t-----------"
puts "\t\t 7 | 8 | 9 "
puts" ###########################################"
class Players
attr_accessor :name, :piece
end
puts "Player one, what is your name?"
player1 = Players.new
player1.name = gets.chomp
player1.piece = "X"
puts "Hello #{player1.name}, you have been assigned #{player1.piece}."
puts "Player two, what is your name?"
player2 = Players.new
player2.name = gets.chomp
player2.piece = "O"
puts "Hello #{player2.name}, you have been assigned #{player2.piece}."
def grid
puts "\t\t #{#entries[1]} | #{#entries[2]} | #{#entries[3]} "
puts "\t\t-----------"
puts "\t\t #{#entries[4]} | #{#entries[5]} | #{#entries[6]} "
puts "\t\t-----------"
puts "\t\t #{#entries[7]} | #{#entries[8]} | #{#entries[9]} "
end
def choice(grid)
name = gets.chomp
name2 = name.to_i
#entries.each do |key,value|
if name2 == key
#entries[key]= "X"
end
end
end
def choice2(grid)
name = gets.chomp
name2 = name.to_i
#entries.each do |key,value|
if name2 == key
#entries[key]= "O"
end
end
end
def turns(player1,player2)
puts "#{player1.name} make your move"
player1 = choice(grid)
puts "#{player2.name} make your move"
player2 = choice2(grid)
end
def win
loop do
turns(player1,player2)
break puts "you win!" if #entries.values[0..2].all?{|move| move == "X"}
end
I think the specific question you're asking is answered like this:
rows = [[0..2],[3..5],[6..8]]
cols = [[0,3,6],[1,4,7],[2,5,8]]
diag = [[0,4,8],[2,4,6]]
(rows + cols + diag).any?{ |line| line.all?{ |cell| #entries[cell] == "X"} }
Also, you can't have two expressions, break and puts before a trailing if statement. Try this:
if ...
puts "You win!"
break
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.
I'm having difficulty in adding underscores in my program. Also what is troubling me is that I can't seem to figure out how to remove the underscores when the user inputs the correct letter.
class Game
attr_reader :guess_count, :is_over, :word_length
def initialize (secret_word)
#secret_word = secret_word
#guess_count = 0
#is_over = false
#word_length = secret_word.length
end
def check_word(guess)
#guess_count += 1
if #secret_word == guess
puts "Congratulations!"
#is_over = true
else
#is_over = false
puts "Sorry, try again!"
end
end
def subtract_guess_count
counter = #word_length - #guess_count
end
end
puts "User 1, What is your secret word?"
secret_word = gets.chomp
anything = Game.new(secret_word)
while !anything.is_over
puts "User 2, Guess the secret word"
guess = gets.chomp
anything.check_word(guess)
if anything.subtract_guess_count == 0
puts "You lose! the correct word was #{secret_word}"
exit!
end
if anything.is_over == false
puts "You have #{anything.subtract_guess_count} left!"
end
end
Major Edit
To create a string of underscores you can do this:
word = ""
1.upto(#secret_word.length) do
word << "_"
end
To replace a character with an underscore (and vice versa) in a ruby string you can use the syntax:
word[i] = "_"
To print a word with spaces between each letter you can use the following:
array = word.split(//)
array.join(" ")
For your code a check_letter function could be useful:
def check_letter (guess)
if (#secret_word[guess])
for i in 0..((#secret_word.length) -1 )
if #secret_word[i] == guess
#progress[i] = guess
end
end
end
show_progress
check_word(#progress)
end
Working code
#! /usr/bin/env ruby
#
class Game
attr_reader :guess_count, :is_over, :word_length, :progress
def initialize (secret_word)
#secret_word = secret_word
#guess_count = 0
#is_over = false
#word_length = secret_word.length
#progress = ""
1.upto(secret_word.length) do
#progress << "_"
end
end
def check_word(guess)
if #secret_word == guess
puts "Congratulations!"
#is_over = true
else
#is_over = false
puts "Sorry, try again!"
end
end
def check_letter (guess)
if (#secret_word[guess])
for i in 0..((#secret_word.length) -1 )
if #secret_word[i] == guess
#progress[i] = guess
end
end
end
show_progress
check_word(#progress)
end
def show_progress
array = #progress.split(//)
word = ""
array.each do |letter|
word << letter + " "
end
puts word
end
def one_less_guess
#guess_count += 1
end
def subtract_guess_count
counter = #word_length - #guess_count
end
end
puts "User 1, What is your secret word?"
secret_word = gets.chomp
anything = Game.new(secret_word)
while !anything.is_over
puts "User 2, Guess the secret word"
guess = gets.chomp
anything.one_less_guess
if guess.length == 1
anything.check_letter(guess)
else
anything.check_word(guess)
end
if anything.subtract_guess_count == 0
puts "You lose! the correct word was #{secret_word}"
exit!
end
if anything.is_over == false
puts "You have #{anything.subtract_guess_count} left!"
end
end
I hope I'm not too annoying . I started ruby 2 weeks ago.
I'm trying to put my calculator in a loop so it restart after calculation ends. Something like "Would you like to try again?"
def add(a, b)
puts "ADDING #{a} + #{b}"
puts "The result is #{a + b}"
end
def arg1()
puts "You chose option 1"
print "please enter first entry "
first_number = gets.to_i
print "Please enter second entry "
second_number = gets.to_i
add(first_number,second_number)
end
def selection()
puts "please enter your option : "
puts "For Adding : 1 "
puts "For Subtacting : 2 "
print "> "
end
selection
options_of_choice = gets.to_i
if options_of_choice == 1
arg1()
elsif options_of_choice == 2
arg2()
else
puts " Restarting"
end
calculator_on = true
while calculator_on
selection
options_of_choice = gets.to_i
if options_of_choice == 1
arg1()
elsif options_of_choice == 2
arg2()
else
puts " Restarting"
end
puts "do you want to try again?"
calculator_on = gets.chomp.downcase == 'y'
end
This is my first foray into computer programming. I have chosen to learn Ruby, and I am enjoying it quite a bit. However, I am a little confused as to why the answer will not output properly in this bit of code.
def addition_function
puts "Which numbers would you like to add?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 + #n2 == #answer
puts "The sum is... #{#answer}"
end
def subtraction_function
puts "Which numbers would you like to subtract?"
#n1 = gets.chomp.to_i
#n2 = gets.chomp.to_i
#n1 - #n2 == #answer
puts "The answer is... #{#answer}"
end
def multiplication_function
puts "Which numbers would you like to multiply?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 * #n2 == #answer
puts "The answer is... #{#answer}"
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
if response == "add" then
addition_function
end
if response == "subtract" then
subtraction_function
end
if response == "multiply" then
multiplication_function
end
I know this is probably horrible code... but could someone help steer me in the right direction?
Consider this code:
def get_int_values
[gets, gets].map{ |s| s.chomp.to_i }
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values.inject(operator)
puts "The answer is... #{ answer }"
The idea is to follow the "DRY" principle: "DRY" means "Don't Repeat Yourself", which the vast majority of the time, is a really good thing.
To help avoid typing mistakes I'd recommend doing something like:
puts "Would you like to [a]dd, [m]ultiply, or [s]ubtract?"
response = gets.chomp
case response[0].downcase
then change the when clauses to match the first letter of the desired operation.
Which will work unless response is empty. You can figure out how to handle that.
another way to obtain answer, once operator is determined, is answer = gets.to_i.send(operator, gets.to_i)
That's true, but here's why I refactored the code the way I did: If, for some reason, there was a need to operate on more than two values, only one thing has to be changed:
[gets, gets].map{ |s| s.chomp.to_i }
could become:
[gets, gets, gets].map{ |s| s.chomp.to_i }
Or, better, could be transformed to something like:
def get_int_values(n)
n.times.map { gets.chomp.to_i }
end
Nothing else will have to change except to find out how many values are needed.
Now, to do it all right would require different text to alert the user that multiple values are expected, but that's easily done by letting letting the user say how many they want to enter, and then prompting for each gets:
def get_int_values(n)
n.times.map.with_index { |n|
print "Enter value ##{ 1 + n }: "
gets.chomp.to_i
}
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
puts "How many values?"
num_of_values = gets.to_i
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values(num_of_values).inject(operator)
puts "The answer is... #{ answer }"
inject can scale up easily because it doesn't presuppose knowledge about the number of values being operated on.
I think with_index in n.times.map.with_index is an artifact you forgot to delete.
It was deliberate but I like this better:
def get_int_values(n)
1.upto(n).map { |n|
print "Enter value ##{ n }: "
gets.chomp.to_i
}
end
Your assignments are on the wrong side of the statement. You should have answer = n1 * n2,
which is not the same as answer == n1 * n2 (this is a check for equality, using ==). The expression always goes on the right, and the variable the result is assigned to goes on the left -- this is pretty much universal, but not necessarily intuitive coming from algebra.
Also: using an # prior to a variable name differentiates it as an instance variable, or member, of a class. From what you've shown here you don't need to include those, just normally scoped variables are required for this use.
Check out this question for more on that part.
The "#" sigil is used to indicate a class instance variable, you have no class so don't use it.
#n1 + #n2 == #answer
Is a boolean expression evaluating whether #n1 + #n2 is equal to #answer.
It will evaluate to true or false.... but you don't make use of the answer.
What you want is ...
answer = n1 + n2
I strongly recommend you always run Ruby with the -w option. It will save you much much heartache.
Please indent your "end"'s to match your "def" (or "if").
You repeat n1 = gets.chomp.to_i all over the place, do it once and pass the answers as a parameter...
response = gets.chomp
n1 = gets.chomp.to_i
n2 = gets.chomp.to_i
if response == "add" then
addition_function( n1, n2)
elsif...
A few suggestions not mentioned by others:
Shorten your method (not "function") names and use verbs (e.g., add instead of addition_method).
As well as using local variables rather than instance variables (mentioned by others), eliminate them where you can. For example, you could simplify
.
def add
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{answer}"
end
to
def add
puts "Which numbers would you like to add?"
puts "The sum is... #{gets.to_i + gets.to_i}"
end
Notice I've used the Ruby convention of indenting two spaces.
You don't need chomp here (though it does no harm), because "123followed by \n or any other non-digits".to_i => 123.
A case statement would work well at the end (and let's loop until the user chooses to quit):
.
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
case gets.chomp
when "add"
add
when "subtract"
subtract
when "multiply"
multiply
when "quit"
break
end
or just
def quit() break end
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
send(gets.chomp)
end
Here we do need chomp. You could replace loop do with while true do or use other equivalent constructs.
class Calculator
def Calc
puts"==well come to mobiloitte calculator=="
puts "enter the first operand:"
#op1 = gets.chomp
return if #op1=="q"
#o1=#op1.to_i
puts "entre the second operand:"
#op2 = gets.chomp
return if #op2=="q"
#o2=#op2.to_i
strong text puts "enter any one operator of your choice (add,sub,mul,div,mod)"
operator = gets.chomp
case operator
when 'add' then #s=#o1+#o2 ; puts "\n ##o1 + ##o2 =##s"
when 'sub' then #t=#o1-#o2 ; puts "\n ##o1 - ##o2 =##t"
when 'mul' then #l=#o1*#o2 ; puts "\n ##o1 * ##o2 =##l"
when 'div' then #r=#o1/#o2 ; puts "\n ##o1 \ ##o2 =##r"
when 'md' then #d=#o1%#o2 ; puts "\n ##o1 % ##o2 =##d"
else
puts"invalide input"
end
end
end
obj= Calculator.new
$f=obj.Calc
You are using #n1 + #n2 == #answer to try and set the answer. What you want to do is #answer = #n1 + #n2.
= is assignment, == is a comparison operator.
Also, you will need to #n1 = gets.chomp.to_i. This will convert your input to an integer from a string. Do that with #n2 as well.
You also do not need to use the # before each of your variables. That should only be used when you are dealing with classes, which you do not appear to be doing.
print "enter number 1 : "
n1 = gets.chomp.to_f
print "enter number 2 : "
n2 = gets.chomp.to_f
print "enter operator: "
op = gets.chomp
if op == '+'
puts "#{n1} + #{n2} = #{n1 + n2}"
elsif op == '-'
puts "#{n1} - #{n2} = #{n1 - n2}"
elsif op == '*'
puts "#{n1} * #{n2} = #{n1 * n2}"
elsif op == '/'
puts "#{n1} / #{n2} = #{n1 / n2}"
end
puts "Would you like to
0 ---- [exit],
1 ---- [add],
2 ---- [subtract],
3 ---- [multiply],
4 ---- [divide]"
response = gets.chomp
case response.downcase
when '1'
def addition_function
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{n1} + #{n2} = #{answer}"
end
addition_function()
#Subtract
when '2'
def subtraction_function
puts "Which numbers would you like to subtact?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 - n2
puts "The subtraction is... #{n1} - #{n2} = #{answer}"
end
subtraction_function()
#Multiply
when '3'
def multiplication_function
puts "Which numbers would you like to multiply?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 * n2
puts "The multiplication is... #{n1} * #{n2} = #{answer}"
end
multiplication_function()
#Division
when '4'
def division_function
puts "Which numbers would you like to divide?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 / n2
puts "The division is... #{n1} / #{n2} = #{answer}"
end
division_function()
else '0'
puts "Exit! Thank You for using us!"
end
#ruby script to do the calculator
puts " enter the number1"
in1=gets.to_i
puts " enter the number2"
in2=gets.to_i
puts "enter the operator"
op=gets.chomp
case op
when '+'
plus=in1+in2
puts "#{in1+in2}"
#puts "#{plus}"
when '-'
min=in1-in2
puts "#{min}"
when '*'
mul= in1*in2
puts "#{mul}"
when '/'
div=in1/in2
puts "#{div}"
else
puts "invalid operator"
end
begin
puts 'First number:'
a = $stdin.gets.chomp.to_i
puts 'Second number:'
b = $stdin.gets.chomp.to_i
operation = nil
unless ['+', '-', '*', '/', '**'].include?(operation)
puts 'Choose operation: (+ - * /):'
operation = $stdin.gets.chomp
end
result = nil
success = false
case operation
when '+'
result = (a + b).to_s
when '-'
result = (a - b).to_s
when '*'
result = (a * b).to_s
when '/'
result = (a / b).to_s
when '**'
result = (a**b).to_s
else
puts 'There is not such kind of operation'
end
success = true
puts "Результат: #{result}"
rescue ZeroDivisionError => e
puts "You tried to devide number by zero! Error: #{e.message}"
end
if success
puts "\nSuccess!"
else
puts "\nSomething goes wrong :("
end
puts ("plz enter a number :")
num1 = gets.chomp.to_f
puts ("plz enter a another number")
num2 = gets.chomp.to_f
puts ("plz enter the operation + , - , x , / ")
opp = gets.chomp
if opp == "+"
puts (num1 + num2)
elsif opp == "-"
puts (num1 - num2)
elsif opp == "x"
puts (num1 * num2)
elsif opp == "/"
puts (num1 / num2)
else puts ("try again :|")
end