I have a class called PolynomialElements and inside that class I have a method called printElement that has a puts statement that print two variables. The puts statement is printing the variables on different lines. How do I get puts to print the two variables on one line. My code is below, it is line #5 where the puts statement is.
class PolynomialElements
attr_accessor :element, :size
def printElement
puts "#{element}x^#{size}"
end
end
askAgain = true
polyArray = Array.new
while askAgain
puts "How many numbers do you want to enter? "
numString = gets
num = numString.to_i
while num > 0
puts "Enter a value for the Polynomial "
value = gets
polyArray.push(value)
num -= 1
end
sizeOfArray = polyArray.length
polyArray.each do |x|
var = PolynomialElements.new
var.element = x
sizeOfArray -= 1
var.size = sizeOfArray
var.printElement
end
puts "Enter y to enter new number or anything else to quit"
cont = gets
if cont.chomp != "y"
askAgain = false
else
polyArray.clear
end
end
In the while loop change:
value = gets
to:
value = gets.chomp
You will then get:
Enter a value for the Polynomial
3
1x^2
2x^1
3x^0
Related
I'm writing this script to build a tic-tac-toe game. This is only the beginning (no turns yet). I want to let the user input again if the previous input is invalid.
def display_board(board)
first_row = " #{board[0]} | #{board[1]} | #{board[2]} "
second_row = " #{board[3]} | #{board[4]} | #{board[5]} "
third_row = " #{board[6]} | #{board[7]} | #{board[8]} "
row_divider = "-----------"
puts first_row
puts row_divider
puts second_row
puts row_divider
puts third_row
end
def valid_move?(board,index)
if (index >= 0) && (index <= board.length - 1) && (position_taken?(board,index) != FALSE)
return TRUE
else
return FALSE
end
end
def input_to_index(user_input)
index = user_input.to_i - 1
return index
end
def move(board, index, character = "X")
board[index] = character
end
def position_taken?(board,index)
if (board[index] == "X") || (board[index]=="O")
return FALSE
end
end
def turn(board)
puts "Please enter 1-9:"
user_input = gets.strip
index = input_to_index(user_input)
while valid_move?(board,index) == FALSE
puts "invalid"
turn(board)
end
move(board, index, character = "X")
display_board(board)
end
I am stuck on the while loop. If I input an invalid input and then a valid input, it runs through the while loop instead of ending the program. It should be true. The problem is fixed if I use an if statement instead of a while loop, but I want to learn to use while loops better.
Because you call "turn" (internal) from "turn" (external) and then the internal "turn" called is valid but the board and index on the external
"turn" didn't change.
try this:
def turn(board)
loop do
puts "Please enter 1-9:"
user_input = gets.strip
index = input_to_index(user_input)
if valid_move?(board,index) == TRUE
break
end
puts "invalid"
end
move(board, index, character = "X")
display_board(board)
end
so here is what i want to do.
I am trying to accomplish so the letter variable gets added to the array each time it runs. The issue is, the variable letter keeps getting re written overtime the loop runs again. So if i type āgā so the variable letter is āgā, it'll put that variable in the array then run it again and repeat there process. So after the loop run 5 times, i want the array to be [l,g,e,f,g]. But instead it gets replaced everytime so instead of array being [l,g,e,f,g], its just [g] cuz thats what the variable letter is currently.
def checkLetter(word)
x = 0
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters = []
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end
puts allLetters.inspect
end
puts "enter a word"
word = gets.chomp
checkLetter(word)
You need to move allLetters = [] outside of your loop
def checkLetter(word)
x = 0
allLetters = [] # look here
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end
could you help me out, please?
I want to write Ruby code in such a way that when I say the word "BYE!" 3 times in a row, it terminates the program.
My code is below
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
request = gets.chomp
while request != "BYE!"
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
Any I could amend the code to follow the rules I want?
Check if this is what you want. and tell me if any error occurs. this may be the rough code
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
counter = 0
request = gets.chomp
while counter < 3
counter += 1 if request.eqls?("BYE!")
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
puts 'If you type bye 3 times, this program will terminate'
bye_counter = 0
loop do
input = gets.chomp
if input == 'bye'
bye_counter += 1
else
bye_counter = 0
end
break if bye_counter == 3
end
I would do something like this:
quotes = File.readlines('quotes.db')
counter = 0
puts 'What?'
loop do
print '>'
request = gets.chomp
if request == 'BYE!'
counter += 1
break if counter >= 3
else
counter = 0
end
puts quotes.sample
end
I'm new to programming in Ruby and I decided to learn to build a hangman game, but I have a problem when comparing two strings, one that comes from a gets (If I do it for me code works normal) and one that is defined.
this is my codes:
this is my 'main':
require_relative("Ahorcado")
juego = Ahorcado.new()
juego.decirPalabra
while juego.hayVidas?
juego.imprimir
lectura = gets
lectura = lectura.to_s;
juego.preguntar lectura
end
puts juego.resultado
And the Ahorcado.rb
class Ahorcado
def loadVariables
#palabras = ["java","ruby","python","go"]
#adivinados = []
#gano = false
#vidas = 7
end
def initialize
loadVariables();
#palabra = #palabras[rand(#palabras.length)].split("")
puts "Se ha iniciado un juego"
#tamano = #palabra.length
puts "Existen #{#tamano} letras"
iniciar
end
def decirPalabra
puts #palabra
end
def preguntar letra
#vidas -= 1
letra = letra.to_s
temp = #palabra.join
puts temp.eql?(letra) # -> Allways false
if letra == #palabra.join then
#gano = true
puts "gano"
else
for i in 0...#tamano
if letra.eql?(#palabra[i]) then #Allways false
#adivinados[i] = true
#vidas += 1
else
puts "Incorrecto intente otra vez"
end
end
end
end
def comparar letra
#temp = letra;
puts #temp == #palabra[0]
end
def iniciar
for i in (0...#tamano)
#adivinados[i] = false;
end
end
def hayVidas?
return #vidas > 0
end
def resultado
#gano;
end
def imprimir
for i in (0...#tamano)
if #adivinados[i] then
print #palabra[i]+" "
else
print "_ "
end
end
puts
end
end
Thanks for yours answers, and sorry if i wrote bad some sentences, i don't speak english
When you do a "gets", lectura contains newline character in the end. Trying doing a "chomp" on lectura :-
lectura = lectura.chomp
and try again. So that all the newline characters are removed. You can also use "bytes" to see the exact characters in your string for debugging purposes.
puts lectura.bytes
Refer:- http://ruby-doc.org/core-2.0/String.html#method-i-chomp
class UnitCircle
def prompt
puts "Enter a number: "
#number = gets
#number = #number.to_i
puts "Enter a trigonometric equation to perform on that number: "
#eqn = gets
end
end
uc = UnitCircle.new
uc.prompt
num = Math.send(uc.instance_eval {#eqn}, uc.instance_eval {#number})
When I try to run it with say,
#number = 30
#eqn = sin
I get a no method error, why?
class UnitCircle
def prompt
puts "Enter a number: "
#number = gets.chomp
#number = #number.to_i
puts "Enter a trigonometric equation to perform on that number: "
#eqn = gets.chomp
end
end
gets method will include the new line symbol "\n". So you have to chomp it.
If you do not chomp, you will end up calling method "sin\n" instead of "sin"