How to get rid of a nested loop to make an arithmetic series more efficient? - ruby

I am pretty new to programming so bear with me, please.
So this is the code I have right now, I would like to know how to combine the two loops in the middle without changing the function of the program.
entry = " "
while entry != "q"
print "enter a number: "
num = gets.to_i
for x in 1..num
sum = 0
end
for y in 1..x
sum = sum + y
puts sum
end
print "press any key to continue (q to quit): "
entry = gets.chomp
end
Any help would be greatly appreciated!
Thank you!
Edit:
I guess I should clarify the function of this program; the user types in a number and then it calculates the value of each arithmetic series up to and including the number that the user put in.
So it if I type in 3 the result should display like this:
1
3
6
Sorry for the confusion!

Assuming that you want to calculate and puts a sum of numbers from 1 to the input number, I suggest following:
while entry != "q"
print "enter a number: "
num = gets.to_i
puts (1..num).sum
print "press any key to continue (q to quit): "
entry = gets.chomp
end
For edited question solution could be:
while entry != "q"
print "enter a number: "
num = gets.to_i
(1..num).inject(0) do |res, e|
res += e
p res
end
print "press any key to continue (q to quit): "
entry = gets.chomp
end

Related

Ruby Number Guessing Game

I have tried to make a number guessing game using ruby but it seems to be looping all over again after the user gets the correct answer, here's my code and thanks in advance!
require './input_functions'
def check (rno,input)
x = 1
while (x == 1)
y = 0
if (rno > input)
puts("Try a bigger number")
input = gets.chomp.to_i
y = y + 1
x = 1
else
if (rno < input)
puts("Try a smaller number")
input = gets.chomp.to_i
y = y + 1
x = 1
else
if(rno == input)
puts("Bingo!")
x = 0
end
end
end
end
return
end
def main
rno = rand(100)
input = read_integer("Enter an integer between 0 and 100: ")
check(rno,input,y)
times = check(rno,input,y)
puts ("You have tried " + times.to_s + " times.")
end
main
The main problems are:
You call check method two times within main method, you need to remove the first one.
You need to move y = 0 out of while loop to be able to return it.
Tried to simplify your code a bit, and you could try to improve it even more.
def check(rno, input)
x = 1
y = 0
while x == 1
if rno == input
puts "Bingo!"
x = 0
else
if rno > input
puts "Try a bigger number"
else
puts "Try a smaller number"
end
input = gets.chomp.to_i
y = y + 1
end
end
return y
end
def main
rno = rand(100)
input = read_integer("Enter an integer between 0 and 100: ")
times = check(rno, input)
puts ("You have tried " + times.to_s + " times.")
end

Reading word into an array [ruby]

Trying to create a ceaser cipher in Ruby.
The problem I'm facing is that when the program reaches the while loop, it only performs the desired operation on the very last letter of the inputted word. Before I delve further into what I've tried, please find the code:
#!/usr/bin/ruby
#print 65.chr ASCII code for A
#print 97.chr ASCII code for a
a = 0
b = 97
d = []
e = 0
# Just to print the alphabet alongside the ASCII value
# (For sanity checking)
while a <= 25
print b.chr + " "
print b.to_s + "\n"
a = a + 1
b = b + 1
end
puts "\n Please enter a word to translate"
word = gets.strip
# The desired effect is to move the letter along by key value
puts "Please enter a key"
k = gets.chomp.to_i
# In its current state, what happens is only the last char
# is moved along by the key value.
while e <= word.length
word.each_byte do |c|
d[e] = c + k
end
e = e + 1
end
puts d
I'm thinking that the problem lies with the logic for the while loop. The way I am going to attack this is by reading the pre-converted word into an array, as opposed to using the .each_byte object.
I don't know how to do that and the guides/questions I've found don't quite answer the question. If anyone knows how to do this, or knows a better way of solving this- I'd be much appreciative.
you don't need the last while loop
word.each_byte do |c|
d[e] = c + k
e = e + 1
end
Something a bit more verbose:
alphabet = ('a'..'z').to_a
new_word = ''
puts "\n Please enter a word to translate"
word = gets.strip
puts "Please enter a key"
k = gets.chomp.to_i
word.split('').each_with_index do |letter, index|
alphabet_index = alphabet.index(letter)
new_index = alphabet_index + key
new_word[index] = alphabet[new_index]
end
puts "Your translated word is #{new_word}"
Caesar cipher is a simple shift cipher
word.each_byte do |c|
p c + k
end
Managed to get it working, thanks for all the help... Code for anyone interested:
#!/usr/bin/ruby
#print 65.chr A
#print 97.chr a
a = 0
b = 65
y = 97
d = []
e = 0
while a <= 25
print y.chr + " = " + y.to_s + " "
print b.chr + " = " + b.to_s + " " + "\n"
a = a + 1
b = b + 1
y = y + 1
end
puts "\n Please enter a word to translate"
word = gets.strip
puts "Please enter a key"
k = gets.chomp.to_i
word.each_byte do |c|
d[e] = c + k
e = e + 1
end
print "\n"
a = 0
arlen = d.count
while a != arlen
print d[a].chr
a = a + 1
end
print k

Ruby looping program gives error

Here's what I wrote to check if a number is prime or not
print "Enter number : "
num = gets.chomp
i = 1
boo = true
while (i<num)
if (i%num==0)
boo=true
end
i++
end
if (boo==true)
puts (num+"is a prime number")
else
puts (num+"is not a prime number")
end
This gives an error, how can I fix it?
The output from cmd prompt:
Some problems:
++ operator doesn't exist in Ruby, you can use += 1 instead
your num is a string, you can make it a number with to_i method, like num.to_i
if the reminder of your number divided by a precedent number is zero you should set to false, not true
if you start at 1 your number will result always prime
Anyway, in a more idiomatic Ruby you can write this code something like
print "Enter number : "
num = gets.chomp.to_i
prime = (2..num - 1).all? { |i| num % i != 0 }
if prime
puts "#{num} is prime"
else
puts "#{num} is not prime"
end

How to build a simple menu-based console application?

It's been a week since I am learning Ruby. It's an awesome language and I am enjoying it.
I am still a noob. Here's a question:
I want a Console Application in Ruby to ask users to hit Num-Keys to choose options like a program with five functions. First four functions for SUM, SUB, MUL and DIV and last one is for returning to main menu.
I tried to write code but I failed. Here is the code:
puts "Choose Option(Press the num key)\n
1. For SUM\n
2. For SUB\n
3. For MUL\n
4. For DIV\n
5. For Main Menu"
$x = 22
$y = 32
def gloabl_f(n) # <= global function start here
def sum(x,y) # <= SUM function
return x+y
end
def sub(x,y) # <= SUB function
return x-y
end
def mul(x,y) # <= MUL function
return x*y
end
def div(x,y) # <= DIV function
return x/y
end
def Main_Menu()
return puts "Choose Option(Press the num key)\n
1. For SUM\n
2. For SUB\n
3. For MUL\n
4. For DIV\n
5. For Main Menu"
end
n = gets.to_i
if n == 1
puts sum(22,32)
end
end # <= global function end here
Basically, I want the user to input two numbers first, and then to be able to choose an option of 1,2,3,4,5 by hitting the numeric keys related to above functions.
Some general points
It isn't very idiomatic to define methods inside of functions
You're never calling neither gloabl_f nor Main_Menu, you just define them.
Here's a sample solution:
def get_numbers
puts "First number:"
x = gets.chomp.to_i
puts "Second number:"
y = gets.chomp.to_i
yield(x,y)
end
def sum(x,y)
x + y
end
puts "Choose Option:
1. For SUM
2. For SUB
3. For MUL
4. For DIV
5. Exit
"
n = gets.chomp.to_i
case n
when 1
get_numbers do |x,y|
puts "Sum: #{sum(x,y)}"
end
when 2
# code
when 3
# code
when 4
# code
else
puts "Exiting"
end
I left the other options for you to implement.
puts "Choose Option(Press the num key)\n
1. For SUM\n
2. For SUB\n
3. For MUL\n
4. For DIV\n
5. For Main Menu"
x = 22
y = 32
n = gets.chomp.to_i
if n == 1
puts x + y
end

If type is character I want to puts error

puts "Let's sum many numbers"
sum = 0
num = 0
while(num != 'x')
puts "Press a number and then Enter if you exit press 'x'"
num = gets.chomp
if num != 'x'
num = num.to_i
print "#{sum} + #{num} = "
sum += num
puts "#{sum}"
elsif num == 'x'
puts "Total sum is #{sum}"
break
else
puts "error!"
end
end
I want to make code to show error If user press char except 'x'.
How should I do?
Change your first if to a condition that checks if the input is a number, e.g.
if num =~ /\A[0..9]+\z/ # or /\A\d+\z/
The way your code is currently, all strings except 'x' are treated as number -- with value 0 in case they aren't really numbers:
'foobar'.to_i # => 0

Resources