6 ms·
Show HN: NSString + Ruby
- mamcx 13y agoAdd a String format one, then is set!
- thingsdoer 13y agoStill don't have a clever implementation.
- mikeash 13y agoUnfortunately, although there's no particular reason for it, you're not allowed to write a method that takes only variadic arguments. This doesn't work: - (NSString *)format: ...; It would be oh-so convenient, meaning you could write formatting operations like this: newstr = [@"%d %@ %s" format: 42, @"blah", "yep"]; Given the constraints we have to work with, I'd say your best bet would be to simply write a function: newstr = fmt(@"%d %@ %s", 42, @"blah", "yep");
- thingsdoer 13y agoUnfortunately, something like "fmt()" isn't really elegant enough, or "objective-c" enough.
- koenigdavidmj 13y agoWhy not just have it be a static method like stringWithFormat? + (id)stringWithFormat:(NSString *)format, ...; This of course already exists, but if you wanted to do a Rubyfied version of it, then just follow the same general pattern.
- thingsdoer 13y agoThe problem people have with the format implementation is that no matter what you do, it's either obtuse shorthand, or incredibly verbose. The reality is, that NSString needs native formatting sugar. Anything else would really just be a hack. I'm not particularly even happy with the [@"Hello ":@"World] syntax, either.
- mikeash 13y agoHere's a crazy idea: newstr = [@"%d %@" format 42, @"blah"]; Implement it as a method that takes a dummy parameter, plus a macro: - (NSString *)format:(int)dummy, ... #define format format:0, Awful way to do it, but the resulting syntax is not entirely terrible.
- thingsdoer 13y agoI'm not super comfortable with breaking message syntax like that. Also, very wary of using a #define with a short oft used keyword in a library that will be imported in majority of headers.
- bennyg 13y agoExactly I just want this: NSString *newS = @"blah " + @(42) + @"!";
- plorkyeran 13y agoComedy option: - (NSString *)format:(id)first, ... { NSUInteger argCount = 0; BOOL prevPercent = NO; for (NSUInteger i = 0; i < [self length]; ++i) { unichar c = [self characterAtIndex:i]; if (prevPercent && c != '%') ++argCount; prevPercent = c == '%'; } NSMutableArray *argArr = [NSMutableArray new]; va_list args; va_start(args, first); for (NSUInteger i = 0; i < argCount; ++i) [argArr addObject:va_arg(args, id)]; va_end(args); switch (argCount) { case 0: return [NSString stringWithFormat:self, first]; case 1: return [NSString stringWithFormat:self, first, argArr[0]]; case 2: return [NSString stringWithFormat:self, first, argArr[0], argArr[1]]; // ... } } Only supports NSObject arguments, obviously. If you actually wanted to do this approach you'd want to do a better job of parsing the format string and use a more cleverer way of storing the args. Or, for the completely insane approach that probably doesn't actually work (on top of being entirely unportable): - (NSString *)format:(id)first, ... { NSUInteger argCount = ...; va_list args; va_start(args, first); void *argList = malloc(sizeof(id) * (argCount + 1)); memcpy(argList, (void*)&first, sizeof(id)); memcpy(argList + sizeof(id), &va_arg(args, void *), sizeof(id) * argCount); va_end(args); NSString *ret = [[NSString alloc] initWithFormat:self arguments:argList]; free(argList); return ret; }
- pdenya 13y agoVery impressive. I didn't know about objectAtIndexedSubscript and objectForKeyedSubscript so I wouldn't have thought this was possible as a category.
- fleitz 13y agoAlmost everything is possible via a category though a lot of it involves hackery with objc/runtime.h
- YoyosForUs 13y agoWow, this looks really useful. Thanks for building this!
- misiti3780 13y agohell yes - im a python guy but this still looks great!
- chrisdevereux 13y agoThey look like convenient additions... but I'd be reluctant to add so many category methods onto a Foundation class. Especially for un-prefixed methods. If a future version of iOS adds an -sum method, for example, you'd better hope it has the exact same semantics as yours, otherwise if the system calls -sum expecting its implementation to be used, bad things (or worse, bad things with no apparent cause) will happen when your implementation is used instead.
- thingsdoer 13y agoI'd correct the category. Also, NSString is not going to change. If it does, it will be rewritten extensively, most probably obsoleting this category.
- thingsdoer 13y agoActually, I might add some protection around this specific case.
- chrisdevereux 13y agoMethods are often added to core classes like NSString. For example, in iOS 6: https://developer.apple.com/library/ios/releasenotes/General/iOS60APIDiffs/index.html https://developer.apple.com/library/ios/releasenotes/General... And you changing the category won't help the versions already out in the wild. Hopefully, automatic updates will mitigate this to some degree but not everyone will turn them on. There are workarounds (like prefixing methods with a pseudo-namespace), but they're all a bit ugly. Might be worth considering though.
- hamxiaoz 13y agoIs 'category' like a extension method in c#?
- fleitz 13y agoYeah, except you can add properties, though you have to do it with objc_(s|g)etAssociatedObject https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html https://developer.apple.com/library/ios/documentation/Cocoa/...
- jph 13y agoSuper! Are you motivated to do more like this? I'll donate $100 to you if you want to continue with NS+Ruby classes.
- thingsdoer 13y agoThere are already a lot of Ruby categories out there. ObjectiveSugar covers a lot of bases. I personally wouldn't import more Ruby categories. The NSString API is a weak point of Cocoa, IMO, but in general I wouldn't like to see a large amount of unique, dependent, astonishing code.
- sarreph 13y agoThis is awesome and, as an Obj-C dev, is yet another thing that makes me want to learn Ruby.
- dennis_vartan 13y agoLike! Much as I love ObjC, reducing verbosity via better syntax can go a long way to making code more readable. For example, I ended up putting together some defines like this after building a bunch of UI programmatically. #define RGB(r, g, b) [NSColor colorWithDeviceRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1] #define RGBA(r, g, b, a) [NSColor colorWithDeviceRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)] RGB(255, 104, 0) may be a bit too C-ish, but it sure beats the long form. Have similar GRAY(x) and GRAYA(x) defines for producing grayscale colors. Definitely interested to see more projects along these lines.
- cheesylard 13y ago#define RGB(r,g,b) RGBA(r,g,b,1)
- wrl 13y agoI prefer: #define RGB(color) \ (((color & 0xFF0000) >> 16) / 255.f), \ (((color & 0x00FF00) >> 8) / 255.f), \ (((color & 0x0000FF)) / 255.f) Pass in an HTML-style color hex triplet.
- stefan_kendall 13y agoI use the same thing to construct NSDecimalNumber instances. N(100.5) instead of [NSDecimalNumber decimalNumberFromString:@"100.5"] SO handy.
- bennyg 13y agoYou can do this now @(100.5) for NSNumber literals.
- dennis_vartan 13y agoAnd even shorter, just @100.5 if what you have is a literal. The parentheses are needed if you're boxing a value, e.g.: @(price + 100.5) In detail: http://clang.llvm.org/docs/ObjectiveCLiterals.html http://clang.llvm.org/docs/ObjectiveCLiterals.html
- w0rdson 13y agoI have to add the obligatory pitch for just using RubyMotion. I use it/love it, and def recommend it for those that have become a bit annoyed with the verbose-ness of obj-c.
- danenania 13y agoI love the idea of RM and would like to give it a try, but I keep hearing murmurs about memory management issues and other little glitches that crop up from time to time. I also hear that these kinds of problems get fixed very quickly, but the idea of being stuck even for a short time while waiting for a proprietary abstraction to be patched up makes me a bit hesitant to reach for it for a serious app. Are these concerns overblown?
- joshdotsmith 13y agoI'm writing a RM app right now and believe these concerns to be overblown. They're overblown in the same way "Rails doesn't scale" is nonsense. The addition of WeakRef to RM helps significantly. And you just have to look out for gotchas. If you want to be really convinced, check out RMQ: https://github.com/infinitered/rmq https://github.com/infinitered/rmq. Has made my life so easy.
- reginaldjcooper 13y agoI believe there was an actual problem with Procs that they fixed a couple of months or so ago. The core developers seem to be active on Twitter, so you could ask the source directly if nobody here knows.
- hboon 13y agoThere were some showstoppers with regards to memory leaks using procs/blocks. There's still a few major ones occasionally where you might be unable to use certain newer frameworks. You'll have to wait for them to fix it. But if you aren't on the bleeding edge, it's not so bad.
- jakobe 13y agoOne thing that irks me is that the author doesn't stick to ObjC naming conventions. Take for example the capitalize methods. In ruby, you have "capitalize" and "capitalize!" to distinguish the immutable and mutable versions. To make this distinction in ObjC, you generally use nouns vs. verbs. So for the equivalent of ruby's "capitalize", you'd use "capitalizedString" (which is in fact provided by NSString). But the mutable version, the equivalent of ruby's "capitalize" should simply be "capitalize", not "capitalizedStringInPlace".
- khangtoh 13y agoWhat's stopping you from submitting a pull request with these suggestions?
- jakobe 13y agoTwo reasons: a) The author might disagree with my asessment. A pull request would imply that I consider it an error, but I think it's more a question of style. b) I already waste too much time on HN. Forking a project, trying to understand all of it, making changes, writing a pull request, etc. would probably take me all day but I need to clean the kitchen and take care of the kids and work on some overdue client work that I have been postponing for far too long.
- fosk 13y agoIf you open a new issue on GitHub, somebody else could fix it.
- thingsdoer 13y ago-(NSString*)capitalizeInPlace; is the actual signature. The reasoning for this is for consistency, while still maintaining autocomplete proximity.
- jakobe 13y agoI'm not really sure I understand; why would calling the method "capitalize" instead of "capitalizeInPlace" be inconsistent? (Also, the comments in the header file and the README file contain the name "capitalizedStringInPlace" instead of "capitalizeInPlace") Another inconsistency is that most mutating methods in ObjectiveC don't return self, but either void or a boolean or an integer that reports if the method succeeded. But I assume that this inconsistency is on purpose because you want to make the methods chainable.
- masklinn 13y agoGood, I was worried people could actually be able to correctly manipulate text through NSString, that fixes it as it's impossible to not break text when using Ruby strings.
- thingsdoer 13y ago>> hn.txt
- andrewgross 13y agoA friend of mine made NSArray extensions with a Ruby syntax a while back. Certainly useful if you find these helpful. https://github.com/nsantorello/nsarray-extensions https://github.com/nsantorello/nsarray-extensions