I'm trying to write some additional collection classes for Ruby, such
as Sets, Trees, Bags, Linked Lists, etc. I've got a working Ruby
version for some of them, but I'm currently attempting to implement a
Set (backed by a Ruby Hash) as a C extension, but I'm not much of a C
programmer and I got a run-time error I can't figure out.
The error occurs when I try to create a new Set with Set.new. My
initialize method takes an optional parameter, which must be an object
that responds to "each", that initializes the set with the specified
values. The Ruby version looks like this:
def initialize(elements = [])
@store = Hash.new
elements.each do |element|
add(element)
end
end
The C version that is *supposed* to emulate this looks like this:
static VALUE set_initialize(int argc, VALUE *argv, VALUE self)
{
VALUE elements;
VALUE store = rb_hash_new();
rb_iv_set(self, "@store", store);
rb_scan_args(argc, argv, "01", &elements);
if (RTEST(elements)) {
rb_iterate(rb_each, elements, set_add, 0);
}
return self;
}
This works fine when I call Set.new with no parameters, but if I call
Set.new([1,2,3]) it fails with the following message:
SetTest#test_initialization SetTest.rb:37: [BUG] Segmentation fault
ruby 1.6.4 (2001-06-04) [i386-cygwin]
0 [sig] ruby 345 open_stackdumpfile: Dumping stack trace to
ruby.exe.stackdump
By the way, my ruby -v is: ruby 1.6.4 (2001-06-04) [i386-cygwin]
Anyone know what I've done wrong?
Thanks,
Jason Voegele