# How to generate rand (random number) between two numbers?

Hi,

How to generate rand (random number) between two numbers?
I mean not between 0 and some number. It should be between some number
(not 0) and some number.

Sincerely,
Asset

On Sep 19, 2011, at 11:52 AM, Асет Асет wrote:

Hi,

How to generate rand (random number) between two numbers?
I mean not between 0 and some number. It should be between some number (not 0)
and some number.

Try this:

irb(main):001:0> def random_number(from, to)
irb(main):002:1> from + rand((to - from).abs)
irb(main):003:1> end
=> #<Rubinius::CompiledMethod random_number file=(irb)>
irb(main):004:0> random_number(6, 9)
=> 6
irb(main):005:0> random_number(6, 9)
=> 7
irb(main):006:0> random_number(6, 9)
=> 6
irb(main):007:0> random_number(6, 9)
=> 6

cr

On Sep 19, 2011, at 1:03 PM, Chuck R. wrote:

irb(main):007:0> random_number(6, 9)
=> 6

cr

Or if you don’t mind opening a core class:
irb1.9.2> class Range
irb1.9.2> def sample
irb1.9.2> span = self.end - self.begin
irb1.9.2> span += 1 unless self.exclude_end?
irb1.9.2> self.begin + rand(span.to_i)
irb1.9.2> end
irb1.9.2> end
#1.9.2 => nil
irb1.9.2> (6…9).sample
#1.9.2 => 7
irb1.9.2> (6…9).sample
#1.9.2 => 8
irb1.9.2> (6…9).sample
#1.9.2 => 7
irb1.9.2> (6…9).sample
#1.9.2 => 9
irb1.9.2> (6…9).sample
#1.9.2 => 8
irb1.9.2> (6…9).sample
#1.9.2 => 7
irb1.9.2> (6…9).sample
#1.9.2 => 6

On Tue, Sep 20, 2011 at 2:19 PM, Rob B.
[email protected] wrote:

(not 0) and some number.
=> 7
irb1.9.2> def sample
irb1.9.2> (6…9).sample
#1.9.2 => 7
irb1.9.2> (6…9).sample
#1.9.2 => 9
irb1.9.2> (6…9).sample
#1.9.2 => 8
irb1.9.2> (6…9).sample
#1.9.2 => 7
irb1.9.2> (6…9).sample
#1.9.2 => 6

I mind, because it’s tricky to get right:

irb(main):022:0> (0.0…0.1).sample
=> 0.0
irb(main):023:0> (0.0…0.1).sample
=> 0.0
irb(main):024:0> (0.0…0.1).sample
=> 0.0
irb(main):025:0> (0.0…0.1).sample
=> 0.0
irb(main):026:0> (0.0…0.1).sample
=> 0.0
irb(main):027:0> (0.0…0.1).sample
=> 0.0
irb(main):028:0> (0.0…0.1).sample
=> 0.0
irb(main):029:0> (0.0…0.1).sample
=> 0.0
irb(main):030:0> (0.0…0.1).sample

i.e. you always get 0 and

irb(main):057:0> (“a”…“o”).sample
NoMethodError: undefined method `-' for "o":String from (irb):11:in `sample’
from (irb):57
from /opt/bin/irb19:12:in `’

At least the logic in Range#sample should be a bit more involved to
either make it fail for floats or only if floats are used with an
inclusive range (…).

Kind regards

robert