public
Last active

Using Obj-C Blocks from MacRuby with Ruby 1.9.2 Syntax

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
# 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)
}
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)}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.