[MacRuby-devel] sprintf, String#%, stringWithFormat, NSLog and friends

Caio Chassot lists at caiochassot.com
Sat Feb 12 05:09:55 PST 2011


So everything in ruby is an object, which means that when using format strings with Objective-C methods like String+stringWithFormat and NSLog, the only formatter that makes sense is "%@". Other formatters generally give unexpected results. E.g. "%d" will print the value of the pointer to the number object. (Or I think that's what it is.)

OTOH ruby itself is, by necessity, smarter in its own handling of format strings. Kernel#sprintf and String#% will generally figure out a way to shoehorn whatever object you're passing into the necessary format, e.g.:

    "%d" % "4" # => "4"
    "%d" % 4.1 # => "4"

Assorted observations:

- Newcomers will inevitably run into sad situations trying to use NSLog with %d and getting really weird numbers.
- The inconsistency between the Objective-C and Ruby behaviors still feels weird even though I understand why it is that way.
- As far as I know, there' no way to specify a non-object argument value (e.g. int) in a ruby method call.
- I'm not sure there's a sane solution to this, e.g. if it's safe to translate ruby objects into the necessary native C types on the fly.
- I wonder if, even after being painfully aware of this dichotomy, there will still be pitfalls that can't be worked around:
  - For example, how do I deal with localizedStringWithFormat? Ruby's native methods aren't locale-aware.
  - Or what about .strings localization files in a mixed Objective-C / MacRuby app?

Has this been given any thought? What are the current plans / recommendations?


More information about the MacRuby-devel mailing list