[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

hash.collect

Joe Ruby

10/28/2006 10:54:00 PM

collect seems to work on a hash:

h = {'a'=>'1', 'b'=>'2'}

params = h.collect {|k, v| "#{k}=#{v}"}.join('&')

Yet collect isn't listed as a method of hash:
http://www.ruby-do...

Is it undocumented, or is some magic going on behind the scenes -- such
as the hash getting converted to an array?

Thanks,
Joe

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

3 Answers

Joel VanderWerf

10/28/2006 11:01:00 PM

0

Joe Ruby MUDCRAP-CE wrote:
> collect seems to work on a hash:
>
> h = {'a'=>'1', 'b'=>'2'}
>
> params = h.collect {|k, v| "#{k}=#{v}"}.join('&')
>
> Yet collect isn't listed as a method of hash:
> http://www.ruby-do...
>
> Is it undocumented, or is some magic going on behind the scenes -- such
> as the hash getting converted to an array?

The Hash class includes the Enumerable module, which defines #collect in
terms of #each. In this case, Hash#each yields key,value pairs, so
#collect does too. It doesn't get converted to an array before map is
called. It does get converted to an array through the normal behavior of
#map:

irb(main):003:0> h={1=>2, 3=>4}
=> {1=>2, 3=>4}
irb(main):004:0> h.map
=> [[1, 2], [3, 4]]

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Justin Collins

10/29/2006 2:59:00 AM

0

Joe Ruby MUDCRAP-CE wrote:
> collect seems to work on a hash:
>
> h = {'a'=>'1', 'b'=>'2'}
>
> params = h.collect {|k, v| "#{k}=#{v}"}.join('&')
>
> Yet collect isn't listed as a method of hash:
> http://www.ruby-do...
>
> Is it undocumented, or is some magic going on behind the scenes -- such
> as the hash getting converted to an array?
>
> Thanks,
> Joe
>
>

No, no real magic: "collect" is part of the Enumerable module, which is
mixed into Hash (and other things) and implements this functionality.

-Justin

[1]http://ruby-doc.org/core/classes/Enume...

matt

10/29/2006 4:12:00 AM

0

Joe Ruby MUDCRAP-CE <joeat303@yahoo.com> wrote:

> collect seems to work on a hash:

You might find something like the following exploratory utility useful:

def method_report(klass)
result = klass.ancestors.inject(Array.new) do |result, anc|
ms = (anc.instance_methods + anc.methods).sort.uniq
result.last[1] -= ms if result.last
result << [anc.name, ms]
end
result.each do |k, v|
puts "----", k
v.each {|m| puts "\s\s#{m}"}
end
end
# and here's how to use it
method_report(Hash)

I'm sure there are much snazzier versions out there. m.

--
matt neuburg, phd = matt@tidbits.com, http://www.tidbits...
Tiger - http://www.takecontrolbooks.com/tiger-custom...
AppleScript - http://www.amazon.com/gp/product/...
Read TidBITS! It's free and smart. http://www.t...