RubyCocoa – to_i and to_s

I’ve been using a lot of RubyCocoa over the past few days, and ran into a few issues that took a while to solve. Blindingly obvious with a bit of foresight, so I figured I’d write this short entry to provide that foresight (or hindsight) to anyone searching for a little help. Generally, the methods … Continue reading “RubyCocoa – to_i and to_s”

I’ve been using a lot of RubyCocoa over the past few days, and ran into a few issues that took a while to solve. Blindingly obvious with a bit of foresight, so I figured I’d write this short entry to provide that foresight (or hindsight) to anyone searching for a little help.

Generally, the methods you call on a RubyCocoa object will return a subclass of OSX::NSObject. You can use puts to print out the value of the object:


some_var = some_osx_nsobject.a_method
puts "a_method returned #{some_var}" # wrong
puts "a_method returned #{some_var} (#{some_var.inspect})" # right

Using the inspect method means you’ll be able to see what kind of object you’re being given. This bit me several times – I’d get an OSX::NSString instance, and when I used the first format above, it would print out its contents, leaving me to believe I had a String (of the Ruby variety). Of course, if I tried to do String type things with it, it would misbehave. Similarly for OSX::NSNumber and Fixnum.

I ended up needing to use to_s and to_i (and occasionally to_a) in order to spit out the right value. Be wary when using to_yaml: you’ll almost definitely have to use one of the to_* methods beforehand.

Leave a Reply