From: Robert Klemme on
On 01.03.2010 20:40, Reiichi Tyrael wrote:
> David Springer wrote:
>> Reiichi Tyrael,
>>
>> Is the range inclusive OR exclusive?
>>
>> Should n1 OR n2 be reurned sometimes or never?
>>
>>> number_to_guess = rand(n1..n2)
> Inclusive!

Sorry, I answered before seeing this email. In that case it should be

irb(main):003:0> low, high = 12, 34
=> [12, 34]
irb(main):004:0> r = low + rand(high + 1 - low)
=> 22

You can also do something like this:

irb(main):012:0> (low..high).to_a.sample
=> 21
irb(main):013:0> (low..high).to_a.sample
=> 27

Although in that case you should store the array somewhere for
efficiency reasons.

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
From: Reiichi Tyrael on
It's work! Thank you David!
But there is no way to do it like in my version "rand(n1..n2)"? It's
more friendly that way XD

--
Posted via http://www.ruby-forum.com/.

From: Siep Korteling on
Reiichi Tyrael wrote:
> It's work! Thank you David!
> But there is no way to do it like in my version "rand(n1..n2)"? It's
> more friendly that way XD

#ruby 1.9
puts (10..20).to_a.sample
#ruby 1.8.6
puts (10..20).to_a.sort_by{rand}.pop

hth,

Siep
--
Posted via http://www.ruby-forum.com/.

From: Brian Candler on
Reiichi Tyrael wrote:
> It's work! Thank you David!
> But there is no way to do it like in my version "rand(n1..n2)"? It's
> more friendly that way XD

Sure:

def myrand(r=nil)
if r.is_a?(Range)
rand(r.last - r.first + (r.exclude_end? ? 0 : 1)) + r.first
else
rand(r)
end
end

Or if you prefer:

module Kernel
alias :orig_rand :rand
def rand(r=nil)
if r.is_a?(Range)
orig_rand(r.last - r.first + (r.exclude_end? ? 0 : 1)) + r.first
else
orig_rand(r)
end
end
end

I suspect it's not implemented in Ruby because it's not obvious what
rand(0.3..5.7) should do.
--
Posted via http://www.ruby-forum.com/.

From: Run Paint Run Run on
Under Ruby 1.9:

10.times.map{ Random.new.rand(20..30) } #=> [26, 26, 22, 20, 30,
26, 23, 23, 25, 22]