Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Created May 16, 2011 12:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seanlilmateus/974340 to your computer and use it in GitHub Desktop.
Save seanlilmateus/974340 to your computer and use it in GitHub Desktop.
Using Obj-C Blocks from MacRuby with Ruby 1.9.2 Syntax
# 1 # Processing enumerated arrays using two blocks
area = "Europe"
timeZoneNames = NSTimeZone.knownTimeZoneNames
areaArray = NSMutableArray.arrayWithCapacity 1
areaIndexes = timeZoneNames.indexesOfObjectsWithOptions NSEnumerationConcurrent,
passingTest: -> (obj, idx, stop) {
tmpStr = obj
tmpStr.hasPrefix area
}
tmpArray = timeZoneNames.objectsAtIndexes areaIndexes
tmpArray.enumerateObjectsWithOptions NSEnumerationConcurrent|NSEnumerationReverse,
usingBlock: -> (obj, idx, stop) {
areaArray << obj.substringFromIndex(area.length+1)
# areaArray << obj[area.size+1..obj.size] #ruby
}
puts "Cities in #{area} time zone: #{areaArray}"
# 2 # Using a block to find matching substrings in a string
musician = "Beatle"
musicDates = NSString.stringWithContentsOfFile "/usr/share/calendar/calendar.music",
encoding:NSASCIIStringEncoding,
error:nil
musicDates.enumerateSubstringsInRange NSMakeRange(0, musicDates.length-1),
options:NSStringEnumerationByLines,
usingBlock:->(substring, substringRange, enclosingRange, stop) {
found = substring.rangeOfString musician
puts "#{substring}" if (found.location != NSNotFound)
}
# 3 # Sorting an array using an NSComparator block
stringsArray = ["string 1","String 21","string 12","String 11","String 02","aTRing 1","aTring 1"]
comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch
finderSort = -> (string1, string2) {
currentLocale = NSLocale.currentLocale
string1Range = NSMakeRange(0, string1.length)
string1.compare(string2, options:comparisonOptions, range:string1Range, locale:currentLocale)
}
puts "finderSort: #{stringsArray.sortedArrayUsingComparator(finderSort)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment