This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: NUM2LONG strangeness
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
While attempting to refactor array.c a little bit, I noticed that the rb_ary_ref() function, the function behind the Array#[] instance method, was performing explicit SYMBOL_P checks. I thought this was odd, because NUM2LONG already has a builtin type check, right?
One little problem - NUM2LONG doesn't seem to mind symbols. If you pass a symbol object to NUM2LONG, it just returns any ol' random number!
#include "ruby.h"
#include <stdio.h>
static VALUE foo_test(VALUE self, VALUE num)
{
long x;
x = NUM2LONG(num);
printf("NUM: %ld\n", x);
return Qnil;
}
void Init_foo(){
VALUE cFoo = rb_define_class("Foo", rb_cObject);
rb_define_method(cFoo, "test", foo_test, 1);
}
# test.rb
f = Foo.new
f.test("foo".to_sym) # 10201! Yikes!
Oofda. Off to the mailing list. Well, knowing this has helped me write better unit tests, at least.