How would I reuse a random number in ruby? - ruby

I am trying to create a random math equation (just with simple addition) where two random numbers are given to you and you need to add them up. My problem is that the two random numbers used for the answer are different from the ones that are used in the equation
puts "Choose the number range (difficulty of the equation)"
difficulty = gets.chomp
a = rand(difficulty)
b = rand(difficulty)
answer = a + b
puts "#{a} + #{b}"
UserAnswer = gets.chomp
if UserAnswer == answer
puts "good"
else
puts "bad"
end

Your problem has nothing to do with random numbers. The problem is that you are comparing a number (the sum of the random numbers) with a string (from the user input). You should replace the relevant line with:
UserAnswer = gets.to_i
By the way, I don't see any reason to use a constant here. It would most likely be better using a local variable like user_answer.

Try storing the of a and b in other two variables like a_aux and b_aux, and then refer to these instead of a and b everytime you would use a and b.

Related

returning the sum of a users input until they say stop

I am trying to create something that constantly takes a users input until they say stop. Then, add all of the previous numbers together. This is what I have so far:
arr = []
puts "Give me a number:"
while input = gets.chomp
if input == "stop"
break
else
puts "Give me a number:"
arr << input
end
end
sum = arr.inject(:+)
puts sum
This is working fine up until adding the numbers together. The arr.inject(:+) seems to be joining the numbers together rather than adding.
For example, when in the while loop, I am entering 1, 2 and 3 into the gets.chomp, but the program is returning 123 rather that 6.
Where am I going wrong?
arr.inject(0) { |sum,e| sum + e.to_i }
a bit more verbose but your problem is that reading from input == String and you want Integer.
Other solution could be
arr.map(&:to_i).inject(:+)
But the first one is more efficient but less fancy.
It is the combination of
arr << input
and
arr.inject(:+)
For example, if you change the first one to:
arr << input.to_i
then it would not be wrong any more.

How do you add to a Ruby array based on users input?

I am asking the user to input a number and based on that number I want to add certain players to my game.
class Player
def players_playing
players = []
puts('How many players are playing?')
players_amount = gets.chomp
for i in range(players_amount)
puts ('What is the players name')
name = gets.chomp
players.push(name)
end
end
end
So if they enter 3. Then the code should loop through 3 times and ask the user for names. e.g.
What is the players name? Rich
What is the players name? Tom
What is the players name? Charles
Then it would have players = ['Rich', 'Tom', 'Charles']
any ideas why my code is not correct? ( i figure it is to do with the range part maybe)
There are some mistakes in your code:
At first you are asking for a number, however players_amount is a string. You should convert it using the to_i method.
Then, for iterating over a range, there are several ways of doing it in Ruby, but there is no keyword range as in Python. For iterating over a range (that is, an interval), use:
# Exclusive:
(0...3).each do |i|
puts i
end
# 0
# 1
# 2
# Inclusive:
(0..3).each do |i|
puts i
end
# 0
# 1
# 2
# 3
So, instead of your for loop, just write (0...players_amount).each do.
With those modifications, the program has the expected behaviour. However, if you want the name to appear on the same line of the question, use print instead of puts because puts adds automatically a line break at the end of the string.
I would add a complement to T. Claverie's answer. In this case I guess you only need to iterate a certain number of times and do nothing with the iteration index. That way, I would replace the for loop in your code with the following:
players_amount.times do
puts ('What is the players name')
name = gets.chomp
players.push(name)
end
Hope it helps.

Building a ruby factorial calculator

I'm working on writing a factorial program in ruby and I'm trying to write it where it does as follows:
Asks the user to enter a value to perform factorial on
takes in that value entered
performs factorial on it
and 4. returns the factorial value using "puts"
My goal is to get this to work then expand on this by building it out to include other statistical functions.
So far this is the code I have:
puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"
#N factorial value
def n
n = gets.chomp
end
def fact
n * fact(n-1)
end
puts fact(n)
Fyi, I might add I've seen the generic factorial code available on the web but what I'm trying to do is set it so that the user defines n rather than setting n statically but when I try to do it, my code as above is erroring with the below error message:
"fact" : wrong number of arguments (1 for 0) (ArgumentError)
My apologies for some of the wording and not including a specific question. My question would be 3 parts:
How would I properly write the factorial calculation to operate on the user provided value? (Which I see was answered).
Once the calculation is performed how can I store that value so it persists in case the user wants to recall it for other calculations.
Lastly, are there any good sources for guidance in writing statistical functions in ruby?
Thank you to all for the assistance
No need to declare n using def, simply assign it (e.g. as n = gets.chomp).
You must include a named argument to your fact function, like def fact(x).
The fact(x) function needs a base case since you are using recursion.
You must convert the user input string n to a number, like n.to_i.
puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"
def fact(x)
(x <= 1) ? 1 : x * fact(x-1)
end
n = gets.chomp.to_i
puts "#{n}! => #{fact(n)}"
Simpler way. Just inject numbers from 1 till n.
puts 'Welcome to the Calculator for Ruby'
puts 'Please enter your value to value'
n = gets.chomp.to_i
puts (1..n).inject(:*)
Might no be the best of solutions but here you go
puts "Welcome to the Factorial Calculator for Ruby"
puts "Please enter your value to exaluate"
n = gets.chomp.to_i
def fact(num)
return num <= 1 ? 1 : num * fact(num - 1)
end
puts "The factorial of #{n} is #{fact(n)}

rounding off to the nearest number ruby

def percent_more
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
end
Now that code will tell you what percent more biggest_number is than smallest_number. But the problem is it prints out a long list of decimals, which are a pain to sort through. So if I wanted the code to only show say the first 3 numbers what would I do??
What you want to use is total_percent_more.round like so:
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more.round}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
See the docs for more info :
http://www.ruby-doc.org/core-2.1.2/Float.html#method-i-round
in ruby versions earlier than 1.9 you'll need to use sprintf like so:
puts "Your biggest number is #{sprintf('%.2f', total_percent_more)}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
You can change the amount of decimal places by changing the number.
See docs for more details:
http://www.ruby-doc.org/core-1.8.7/Kernel.html#method-i-sprintf
result = 10/6.0
puts result
printf("%.3f\n", result)
--output:--
1.66666666666667
1.667
Here is an example how to round to 2 decimal places
amount = 342
puts amount.round(2)
If you wanted to round to the nearest 3 decimal places then something like:
puts amount.round(3)

Input string does not match a numerical range

The below ruby code is not working as expected. It doesn't seem to recognise the 1..3 range and is only reading the else condition. If I gave a number instead of a range, it works though. Not sure where I'm going wrong.
print "Enter your cost: "
cost = gets.chomp
case cost
when 1..3
puts "inexpensive"
when 3..5
puts "affordable"
else puts "no comments"
end
You're trying to match a string against an integer range. That's not going to work. Make an integer.
cost = gets.chomp.to_i
The input you get from gets is always a string, so it will never match a number range. To convert it to an integer, do this:
cost = gets.to_i
You can directly put it in case statement like so
case gets.to_i

Resources