Learn Ruby – How To Get a Random Number

 
Ruby has a creator of random numbers (or aleatory) already integrated into its code, which is the method rand. Since version 1.9.3, Ruby added the ability to use ranges as arguments to rand, which produces a more fluid code.

Now we are going to examine some of the ways to create a random number using the rand method and its variations.
 

Ruby – Creating random number using rand

If you call rand directly, you get a float greater than or equal to 0.0 and less than 1.0.


If you put in it an integer argument (such as, for example, rand (7)), you will get an integer value greater than or equal to 0 and less than 7.


If you are looking for a number within a particular range you can use:


Where the initial value is the lower range limit, and the final value will include the higher limit.

If you are looking for a non-inclusive range, you can use 3 points:


This will delete the final value of the random number generation, in this case, 10. You could do the same thing using the previous form and entering the last value that you want to include:


 

Ruby – Creating random number using random

The random.rand works quite similar to rand:


However, when the argument value is a negative integer or zero, this method returns ArgumentError, unlike rand.

Do you know other ways to create random numbers in Ruby? Share your comments in the section below!

If you want to explore other issues, can check our LCTV videos about Ruby. Below we have some examples:

 

You can also subscribe to some channels that broadcasts in Ruby, such as the following:

iamjbeckerRuby random rand programming livecoding.tv

 

 

carlosvigilRuby random rand programming livecoding.tv

 

 

Another cool way to find out interesting things about Ruby is to access our project page!

(Visited 371 times, 3 visits today)
  • Maxim

    Useful. Thank you! =)

Read previous post:
Ruby – Best way to Generate a Random String (1)
Learn Ruby – The Best Way to Generate a Random String

  Whenever you think of the best way to do something, there are different opinions on the subject.  Best in...

Close