K
Kristof Bastiaensen
Hi, I have written a method collect_by.
I am not sure if it already exist, but it is very
usefull. It is a generic version of collect, that
works with any method. Basicly it converts the output
of any block to an Array
class Object
def collect_by(method, *args)
a = []
send(method, *args) { |*o|
a.push(block_given? ?
(yield *o) :
(o.size > 1 ? o : o[0])) }
return a
end
end
Examples:
"a string".collect_byeach_byte)
=> [97, 32, 115, 116, 114, 105, 110, 103]
3.collect_bystep, 20, 4)
=>[3, 7, 11, 15, 19]
(3..7).collect_byeach_with_index)
=> [[3, 0], [4, 1], [5, 2], [6, 3], [7, 4]]
5.collect_bytimes) { rand 100 }
=> [61, 85, 13, 52, 47]
5.collect_bytimes) { |i| i * i }
=> [0, 1, 4, 9, 16]
I am not sure if it already exist, but it is very
usefull. It is a generic version of collect, that
works with any method. Basicly it converts the output
of any block to an Array
class Object
def collect_by(method, *args)
a = []
send(method, *args) { |*o|
a.push(block_given? ?
(yield *o) :
(o.size > 1 ? o : o[0])) }
return a
end
end
Examples:
"a string".collect_byeach_byte)
=> [97, 32, 115, 116, 114, 105, 110, 103]
3.collect_bystep, 20, 4)
=>[3, 7, 11, 15, 19]
(3..7).collect_byeach_with_index)
=> [[3, 0], [4, 1], [5, 2], [6, 3], [7, 4]]
5.collect_bytimes) { rand 100 }
=> [61, 85, 13, 52, 47]
5.collect_bytimes) { |i| i * i }
=> [0, 1, 4, 9, 16]