I’ve come around a strange problem, after upgrading to 2.0.2.
I have subclassed the Array class with this method to extract a random
item (I haven’t made it myself, but it is quite clever):
class Array
def random(weights=nil)
return random(map {|n| n.send(weights)}) if weights.is_a? Symbol
puts length
puts self
weights ||= Array.new(length, 1.0)
total = weights.inject(0.0) {|t,w| t+w}
point = rand * total
zip(weights).each do |n,w|
return n if w >= point
point -= w
end
end
end
If I use it with a simple array like:
arr = [5,8,7,3]
arr.random
It works fine.
But if i try the same with a database extraction I now get an error. As
an example, I have a model called “Banner”:
Sorry I’ve made a slight typo (I was trying to find out what was
happening…) The subclassing should look like this:
class Array
def random(weights=nil)
return random(map {|n| n.send(weights)}) if weights.is_a? Symbol
weights ||= Array.new(length, 1.0)
total = weights.inject(0.0) {|t,w| t+w}
point = rand * total
zip(weights).each do |n,w|
return n if w >= point
point -= w
end
I thought of suggesting that, but he’s trying to do something similar,
but with a parameter to provide a weighted distribution. The rand
method in ActiveSupport only gives a uniform distribution.
It might be useful if this is only used with ActiveSupport to put
something like
I thought of suggesting that, but he’s trying to do something similar,
but with a parameter to provide a weighted distribution. The rand
method in ActiveSupport only gives a uniform distribution.
It might be useful if this is only used with ActiveSupport to put
something like
return rand unless weightt
at the top of the method though.
You’re quite right Rick. The code could do with this refactoring, after
all it IS pre-2.0 - thank you for your bright ideas.
I don’t recall who made this little nice function, but I think I’ll
repost it on the net with modifications.
Carsten
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.