How to create a random number generator in Ruby? I know there are ways to do it like rand(0..9)
to generate a random number from 0 to 9, or rand(0…9)
to generate a random number from 0 to 8. But what if I say rand(0.. *variable*)
to generate a random number from 0 to the value of that variable?
Look at the code below for a clearer example:
Suppose I’m creating a number guessing game
print “Enter a number: “
max_num = gets
max_num.to_i #converting it into an integer to print it out with strings
random_num = rand(0.. **max_num**)
CodePudding user response:
max_num.to_i
does not change the string to an integer. The string is still a string. The method to_i
returns an integer that's not the string.
irb> s = "123"
irb> p s.to_i
123
irb> p s
"123"
What you need to do is to assign the return value to a variable (even the same variable will do) and use that variable, like
max_num = max_num.to_i
random_num = rand(0..max_num)
Actually, in Ruby, though there are lots of methods that can change the internal state of the receiver (like Array#map!
and String#strip!
), there's no method that can change the type of the receiver.
CodePudding user response:
Use Ruby's sample
method.
max = 8
a = [*1..max]
p a.sample
Output
4