rhh
rhh

Reputation: 2008

How call Ruby's internal C methods in Ruby?

I'm trying to create a hash from an array and the documentation for http://ruby-doc.org/ruby-1.9/classes/Array.src/M000744.html shows an internal ruby method called ary_make_hash. The source uses this to diff arrays. The relevant line in the source is: ary_make_hash(to_ary(ary2), 0);

Is there a way to access the ary_make_hash function and other internal Ruby functions from inside Ruby? I ask since I'm trying to convert a huge array to a hash and I'd love to use the built in C methods since they're so much faster. (FYI I can see the speed difference by subtracting two arrays, which internally invokes the converter method). Thanks for any thoughts.

Robert

Upvotes: 3

Views: 513

Answers (3)

Phrogz
Phrogz

Reputation: 303559

Are neither of these variations sufficiently fast? You're not doing very much in Ruby at all, but relying on the built in array-to-hash conversion.

a1 = [[:a,1],[:b,2],[:c,3]]
h1 = Hash[a2]
#=> {:a=>1, :b=>2, :c=>3} 

a2 = a1.flatten
h2 = Hash[*a2]
#=> {:a=>1, :b=>2, :c=>3}     

Upvotes: 1

philosodad
philosodad

Reputation: 1808

That function is static, which, according to this: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/SYNTAX/static.htm

means that it can't be referenced from outside the array.c file.

So in order to use it, you'd have to actually hack the source.

Upvotes: 0

rogerdpack
rogerdpack

Reputation: 66961

in general if it's not in ruby.h, then it's not a "public" api looking for a method called rb_xxx might also help. GL.

Upvotes: 1

Related Questions