Method: Enumerable#max_by
- Defined in:
- enum.c
#max_by {|obj| ... } ⇒ Object #max_by ⇒ Object #max_by(n) {|obj| ... } ⇒ Object #max_by(n) ⇒ Object
Returns the object in enum that gives the maximum value from the given block.
If no block is given, an enumerator is returned instead.
a = %w(albatross dog horse)
a.max_by { |x| x.length } #=> "albatross"
If the n argument is given, minimum n elements are returned as an array.
a = %w[albatross dog horse]
a.max_by(2) {|x| x.length } #=> ["albatross", "horse"]
enum.max_by(n) can be used to implement weighted random sampling. Following example implements and use Enumerable#wsample.
module Enumerable
# weighted random sampling.
#
# Pavlos S. Efraimidis, Paul G. Spirakis
# Weighted random sampling with a reservoir
# Information Processing Letters
# Volume 97, Issue 5 (16 March 2006)
def wsample(n)
self.max_by(n) {|v| rand ** (1.0/yield(v)) }
end
end
e = (-20..20).to_a*10000
a = e.wsample(20000) {|x|
Math.exp(-(x/5.0)**2) # normal distribution
}
# a is 20000 samples from e.
p a.length #=> 20000
h = a.group_by {|x| x }
-10.upto(10) {|x| puts "*" * (h[x].length/30.0).to_i if h[x] }
#=> *
# ***
# ******
# ***********
# ******************
# *****************************
# *****************************************
# ****************************************************
# ***************************************************************
# ********************************************************************
# ***********************************************************************
# ***********************************************************************
# **************************************************************
# ****************************************************
# ***************************************
# ***************************
# ******************
# ***********
# *******
# ***
# *
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 |
# File 'enum.c', line 1843
static VALUE
enum_max_by(int argc, VALUE *argv, VALUE obj)
{
NODE *memo;
VALUE num;
rb_scan_args(argc, argv, "01", &num);
RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
if (!NIL_P(num))
return nmin_run(obj, num, 1, 1);
memo = NEW_MEMO(Qundef, Qnil, 0);
rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
return memo->u2.value;
}
|