I want to know how to use random in ruby.

Asked 2 years ago, Updated 2 years ago, 156 views

How do I make a number from 0 to n in ruby?

random ruby

2022-09-22 22:10

1 Answers

If no factor is given, or max.to_i.abs is 0, return pseudo-random floating point. The range of values returned is [0.0, 1.0].

puts rand

If max.abs is greater than or equal to 1, return pseudo-random integer. The returned value range is [0,max.to_i.abs).

puts rand(100)

If max is in range, return the random number with range.member?(number) == true.

max may be negative or floating point, but may result in different results than expected.

puts rand(-100)
puts rand(-0.5)
puts rand(1.9)

You need to use srand to give seed.

If max is an integer, returns an integer in the range [0, max]. If max is negative unlike the rand of the previous kernel, raise ArgumentError.

puts Random.new.rand(100)

If max is float, return the floating point in the [0.0, max) range.

puts Random.new.rand(1.5)

If max is in range, return the random number with range.member?(number) == true.

prng = Random.new

puts prng.land (5..9) # => [5, 6, 7, 8, 9]
puts prng.land (5...9) # => [5, 6, 7, 8]
puts prng.land (5.0..9.0) # => [5.0, 9.0]
values between puts prng.land (5.0...9.0) # => [5.0, 9.0]


2022-09-22 22:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.