Class: NSObject

Includes:
Kernel

Overview

NSObject is the root class of most Objective-C class hierarchies. Through NSObject, objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.

Direct Known Subclasses

ADInterstitialAd, ARGF, AVAsset, AVAssetExportSession, AVAssetImageGenerator, AVAssetReader, AVAssetReaderOutput, AVAssetResourceLoader, AVAssetResourceLoadingRequest, AVAssetTrack, AVAssetTrackSegment, AVAssetWriter, AVAssetWriterInput, AVAssetWriterInputPixelBufferAdaptor, AVAudioMix, AVAudioMixInputParameters, AVAudioPlayer, AVAudioRecorder, AVAudioSession, AVAudioSessionChannelDescription, AVAudioSessionDataSourceDescription, AVAudioSessionPortDescription, AVAudioSessionRouteDescription, AVCaptureAudioChannel, AVCaptureConnection, AVCaptureDevice, AVCaptureDeviceFormat, AVCaptureInput, AVCaptureInputPort, AVCaptureOutput, AVCaptureSession, AVFrameRateRange, AVMediaSelectionGroup, AVMediaSelectionOption, AVMetadataItem, AVMetadataObject, AVPlayer, AVPlayerItem, AVPlayerItemAccessLog, AVPlayerItemAccessLogEvent, AVPlayerItemErrorLog, AVPlayerItemErrorLogEvent, AVPlayerItemOutput, AVPlayerItemTrack, AVTextStyleRule, AVTimedMetadataGroup, AVVideoComposition, AVVideoCompositionCoreAnimationTool, AVVideoCompositionInstruction, AVVideoCompositionLayerInstruction, Binding, Boxed, CAAnimation, CADisplayLink, CAEmitterCell, CALayer, CAMediaTimingFunction, CATransaction, CAValueFunction, CIColor, CIContext, CIDetector, CIFeature, CIFilter, CIImage, CIVector, CLGeocoder, CLHeading, CLLocation, CLLocationManager, CLPlacemark, CLRegion, CMAttitude, CMLogItem, CMMotionManager, CTCall, CTCallCenter, CTCarrier, CTTelephonyNetworkInfo, Data, Dispatch::Object, EKEventStore, EKObject, EKRecurrenceDayOfWeek, EKRecurrenceEnd, ENV, Encoding, Encoding::Converter, Enumerable::Enumerator, Enumerator, FalseClass, File::Stat, GKAchievement, GKAchievementDescription, GKChallenge, GKChallengeEventHandler, GKInvite, GKLeaderboard, GKMatch, GKMatchRequest, GKMatchmaker, GKNotificationBanner, GKPeerPickerController, GKPlayer, GKScore, GKSession, GKTurnBasedEventHandler, GKTurnBasedMatch, GKTurnBasedParticipant, GKVoiceChat, GKVoiceChatService, IO, MKDirectionsRequest, MKMapItem, MKReverseGeocoder, MKShape, MKUserLocation, MPMediaEntity, MPMediaItemArtwork, MPMediaLibrary, MPMediaPredicate, MPMediaQuery, MPMediaQuerySection, MPMovieAccessLog, MPMovieAccessLogEvent, MPMovieErrorLog, MPMovieErrorLogEvent, MPMoviePlayerController, MPMusicPlayerController, MPNowPlayingInfoCenter, MPTimedMetadata, MatchData, Method, Module, Mutex, NKAssetDownload, NKIssue, NKLibrary, NSArray, NSAssertionHandler, NSAtomicStoreCacheNode, NSAttributedString, NSAutoreleasePool, NSBundle, NSCache, NSCachedURLResponse, NSCalendar, NSCharacterSet, NSCoder, NSCondition, NSConditionLock, NSData, NSDate, NSDateComponents, NSDecimalNumberHandler, NSDictionary, NSEntityDescription, NSEntityMapping, NSEntityMigrationPolicy, NSEnumerator, NSError, NSException, NSExpression, NSFetchedResultsController, NSFileCoordinator, NSFileHandle, NSFileManager, NSFileSecurity, NSFileVersion, NSFileWrapper, NSFormatter, NSHTTPCookie, NSHTTPCookieStorage, NSHashTable, NSIncrementalStoreNode, NSIndexPath, NSIndexSet, NSInvocation, NSJSONSerialization, NSLinguisticTagger, NSLocale, NSLock, NSManagedObject, NSManagedObjectContext, NSManagedObjectID, NSManagedObjectModel, NSMapTable, NSMappingModel, NSMergeConflict, NSMergePolicy, NSMetadataItem, NSMetadataQuery, NSMetadataQueryAttributeValueTuple, NSMetadataQueryResultGroup, NSMethodSignature, NSMigrationManager, NSNetService, NSNetServiceBrowser, NSNotification, NSNotificationCenter, NSNotificationQueue, NSNull, NSOperation, NSOperationQueue, NSOrderedSet, NSOrthography, NSParagraphStyle, NSPersistentStore, NSPersistentStoreCoordinator, NSPersistentStoreRequest, NSPipe, NSPointerArray, NSPointerFunctions, NSPort, NSPredicate, NSProcessInfo, NSPropertyDescription, NSPropertyListSerialization, NSPropertyMapping, NSProxy, NSRecursiveLock, NSRegularExpression, NSRunLoop, NSScanner, NSSet, NSShadow, NSSortDescriptor, NSStream, NSString, NSStringDrawingContext, NSThread, NSTimeZone, NSTimer, NSURL, NSURLAuthenticationChallenge, NSURLCache, NSURLConnection, NSURLCredential, NSURLCredentialStorage, NSURLProtectionSpace, NSURLProtocol, NSURLRequest, NSURLResponse, NSUUID, NSUbiquitousKeyValueStore, NSUndoManager, NSUserDefaults, NSValue, NSValueTransformer, NSXMLParser, NilClass, Object, PKPass, PKPassLibrary, Pointer, Proc, Process::GID, Process::Status, Process::Sys, Process::UID, Random, Range, Regexp, RubyObject, SKDownload, SKPayment, SKPaymentQueue, SKPaymentTransaction, SKProduct, SKProductsResponse, SKRequest, SLRequest, Struct, Thread, ThreadGroup, TopLevel, TrueClass, UIAcceleration, UIAccelerometer, UIAccessibilityElement, UIActivity, UIBarItem, UIBezierPath, UICollectionViewLayout, UICollectionViewLayoutAttributes, UICollectionViewUpdateItem, UIColor, UIDevice, UIDictationPhrase, UIDocument, UIDocumentInteractionController, UIEvent, UIFont, UIGestureRecognizer, UIImage, UIMenuItem, UINavigationItem, UINib, UIPasteboard, UIPopoverController, UIPrintFormatter, UIPrintInfo, UIPrintInteractionController, UIPrintPaper, UIResponder, UIScreen, UIScreenMode, UISearchDisplayController, UIStoryboard, UIStoryboardSegue, UITextChecker, UITextInputMode, UITextInputStringTokenizer, UITextPosition, UITextRange, UITextSelectionRect, UITouch, UnboundMethod

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

+ (Object) initialize

Initializes the receiver before it’s used (before it receives its first message). The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

Returns:

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

- (Object) method_missing(symbol[, *args]) (private)

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. If it is decided that a particular method should not be handled, then super should be called, so that ancestors can pick up the missing method. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

class Roman
  def roman_to_int(str)
    # ...
  end
  def method_missing(methId)
    str = methId.id2name
    roman_to_int(str)
  end
end

r = Roman.new
r.iv      #=> 4
r.xxiii   #=> 23
r.mm      #=> 2000

Class Method Details

+ (String) `

Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.

`date`                   #=> "Wed Apr  9 08:56:30 CDT 2003\n"
`ls testdir`.split[1]    #=> "main.rb"
`echo oops && exit 99`   #=> "oops\n"
$?.exitstatus            #=> 99

Returns:

+ (Object) alloc

Returns a new instance of the receiving class. The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0. You must use an init... method to complete the initialization process. For example: Do not override alloc to include initialization code. Instead, implement class-specific versions of init... methods.For historical reasons, alloc invokes allocWithZone:.

Returns:

  • (Object)

    A new instance of the receiver.

+ (Object) allocWithZone(zone)

Returns a new instance of the receiving class. The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0. You must use an init... method to complete the initialization process. For example: Do not override allocWithZone: to include any initialization code. Instead, class-specific versions of init... methods.This method exists for historical reasons; memory zones are no longer used by Objective-C.

Parameters:

  • zone (NSZone)

    This parameter is ignored.

Returns:

  • (Object)

    A new instance of the receiver.

+ (nil) autoload

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")

Returns:

  • (nil)

+ (String?) autoload?(name)

Returns filename to be loaded if name is registered as autoload.

autoload(:B, "b")
autoload?(:B)            #=> "b"

Returns:

Returns:

  • (Boolean)

+ (Object) autorelease_pool { ... }

autorelease_pool provides memory management funtion like @autoreleasepool in ARC. At the end of the autorelease_pool block, object receives a release message.

str = nil
autorelease_pool {
  str = "hello"
}
puts str           # str has been already released. So, this line will cause crash.

Yields:

+ (Binding) binding

Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. See also the description of class Binding.

def get_binding(param)
  return binding
end
b = get_binding("hello")
eval("param", b)   #=> "hello"

Returns:

+ (Boolean) block_given? + (Boolean) iterator?

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

def try
  if block_given?
    yield
  else
    "no block"
  end
end
try                  #=> "no block"
try { "hello" }      #=> "hello"
try do "hello" end   #=> "hello"

Overloads:

  • + block_given?

    Returns:

    • (Boolean)
  • + iterator?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

+ (Array?) caller(start = 1)

Returns the current execution stack---an array containing strings in the form "file:line" or "file:line: in `method'". The optional start parameter determines the number of initial stack entries to omit from the result.

Returns nil if start is greater than the size of current execution stack.

def a(skip)
  caller(skip)
end
def b(skip)
  a(skip)
end
def c(skip)
  b(skip)
end
c(0)   #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"]
c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"]
c(2)   #=> ["prog:8:in `c'", "prog:12:in `<main>'"]
c(3)   #=> ["prog:13:in `<main>'"]
c(4)   #=> []
c(5)   #=> nil

Returns:

+ (Object) cancelPreviousPerformRequestsWithTarget(aTarget)

Cancels perform requests previously registered with the performSelector:withObject:afterDelay: instance method. All perform requests having the same target aTarget are canceled. This method removes perform requests only in the current run loop, not all run loops.

Parameters:

  • aTarget (Object)

    The target for requests previously registered with the performSelector:withObject:afterDelay: instance method.

Returns:

+ (Object) cancelPreviousPerformRequestsWithTarget(aTarget, selector:aSelector, object:anArgument)

Cancels perform requests previously registered with performSelector:withObject:afterDelay:. All perform requests are canceled that have the same target as aTarget, argument as anArgument, and selector as aSelector. This method removes perform requests only in the current run loop, not all run loops.

Parameters:

  • aTarget (Object)

    The target for requests previously registered with the performSelector:withObject:afterDelay: instance method

  • aSelector (Symbol)

    The selector for requests previously registered with the performSelector:withObject:afterDelay: instance method.

  • anArgument (Object)

    The argument for requests previously registered with the performSelector:withObject:afterDelay: instance method. Argument equality is determined using isEqual:, so the value need not be the same object that was passed originally. Pass nil to match a request for nil that was originally passed as the argument.

Returns:

+ (Object) catch([arg]) {|tag| ... }

catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's tag. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.

def routine(n)
  puts n
  throw :done if n <= 0
  routine(n-1)
end

catch(:done) { routine(3) }

produces:

3
2
1
0

when arg is given, catch yields it as is, or when no arg is given, catch assigns a new unique object to throw. this is useful for nested catch. arg can be an arbitrary object, not only Symbol.

Yields:

  • (tag)

Returns:

+ (Class) class

Returns the class object. Refer to a class only by its name when it is the receiver of a message. In all other cases, the class object must be obtained through this or a similar method. For example, here SomeClass is passed as an argument to the isKindOfClass: method (declared in the NSObject protocol):

Returns:

  • (Class)

    The class object.

+ (Array) classFallbacksForKeyedArchiver

Overridden to return the names of classes that can be used to decode objects if their class is unavailable. NSKeyedArchiver calls this method and stores the result inside the archive. If the actual class of an object doesn’t exist at the time of unarchiving, NSKeyedUnarchiver goes through the stored list of classes and uses the first one that does exists as a substitute class for decoding the object. The default implementation of this method returns nil.You can use this method if you introduce a new class into your application to provide some backwards compatibility in case the archive will be read on a system that does not have that class. Sometimes there may be another class which may work nearly as well as a substitute for the new class, and the archive keys and archived state for the new class can be carefully chosen (or compatibility written out) so that the object can be unarchived as the substitute class if necessary.

Returns:

  • (Array)

    An array of NSString objects that specify the names of classes in preferred order for unarchiving

+ (Class) classForKeyedUnarchiver

Overridden by subclasses to substitute a new class during keyed unarchiving. During keyed unarchiving, instances of the receiver will be decoded as members of the returned class. This method overrides the results of the decoder’s class and instance name to class encoding tables.

Returns:

  • (Class)

    The class to substitute for the receiver during keyed unarchiving.

+ (Boolean) conformsToProtocol(aProtocol)

Returns a Boolean value that indicates whether the receiver conforms to a given protocol. A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols: A class also conforms to any protocols that are incorporated in the protocols it adopts or inherits. Protocols incorporate other protocols in the same way classes adopt them. For example, here the AffiliationRequests protocol incorporates the Joining protocol: If a class adopts a protocol that incorporates another protocol, it must also implement all the methods in the incorporated protocol or inherit those methods from a class that adopts it.This method determines conformance solely on the basis of the formal declarations in header files, as illustrated above. It doesn’t check to see whether the methods declared in the protocol are actually implemented—that’s the programmer’s responsibility.The protocol required as this method’s argument can be specified using the @protocol() directive:

Parameters:

  • aProtocol (Protocol)

    A protocol.

Returns:

  • (Boolean)

    YES if the receiver conforms to aProtocol, otherwise NO.

+ (Object) copyWithZone(zone)

Returns the receiver. This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.

Parameters:

  • zone (NSZone)

    This argument is ignored.

Returns:

+ (String) description

Returns a string that represents the contents of the receiving class. The debugger’s print-object command invokes this method to produce a textual description of an object.NSObject’s implementation of this method simply prints the name of the class.

Returns:

  • (String)

    A string that represents the contents of the receiving class.

+ (nil) display(port = $>)

Prints obj on the given port (default $>). Equivalent to:

def display(port=$>)
  port.write self
end

For example:

1.display
"cat".display
[ 4, 5, 6 ].display
puts

produces:

1cat456

Returns:

  • (nil)

+ (Object) raise + (Object) raise(string) + (Object) raise(exception[, string [, array]]) + (Object) fail + (Object) fail(string) + (Object) fail(exception[, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller

+ (String) format(format_string[, arguments...]) + (String) sprintf(format_string[, arguments...])

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result.

The syntax of a format sequence is follows.

%[flags][width][.precision]type

A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.

The field type characters are:

Field |  Integer Format
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..1'.
  B   | Equivalent to `b', but uses an uppercase 0B for prefix
      | in the alternative format by #.
  d   | Convert argument as a decimal number.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..7'.
  u   | Identical to `d'.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..f' (representing an infinite string of
      | leading 'ff's).
  X   | Equivalent to `x', but uses uppercase letters.

Field |  Float Format
------+--------------------------------------------------------------
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  f   | Convert floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Convert a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  a   | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
      | which is consisted from optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to `a', but use uppercase `X' and `P'.

Field |  Other Format
------+--------------------------------------------------------------
  c   | Argument is the numeric code for a single character or
      | a single character string itself.
  p   | The valuing of argument.inspect.
  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.
  %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:

Flag     | Applies to    | Meaning
---------+---------------+-----------------------------------------
space    | bBdiouxX      | Leave a space at the start of
         | aAeEfgG       | non-negative numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all           | Specifies the absolute argument number
         |               | for this field.  Absolute and relative
         |               | argument numbers cannot be mixed in a
         |               | sprintf string.
---------+---------------+-----------------------------------------
 #       | bBoxX         | Use an alternative format.
         | aAeEfgG       | For the conversions `o', increase the precision
         |               | until the first digit will be `0' if
         |               | it is not formatted as complements.
         |               | For the conversions `x', `X', `b' and `B'
         |               | on non-zero, prefix the result with ``0x'',
         |               | ``0X'', ``0b'' and ``0B'', respectively.
         |               | For `a', `A', `e', `E', `f', `g', and 'G',
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+        | bBdiouxX      | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX      | Pad with zeros, not spaces.
         | aAeEfgG       | For `o', `x', `X', `b' and `B', radix-1
         | (numeric fmt) | is used for negative numbers formatted as
         |               | complements.
---------+---------------+-----------------------------------------
*        | all           | Use the next argument as the field width.
         |               | If negative, left-justify the result. If the
         |               | asterisk is followed by a number and a dollar
         |               | sign, use the indicated argument as the width.

Examples of flags:

# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123)  #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"

# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123)   #=> "173"
sprintf("%#o", 123)  #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123)  #=> "..7605"
sprintf("%#o", -123) #=> "..7605"

# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123)   #=> "7b"
sprintf("%#x", 123)  #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123)  #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0)    #=> "0"

# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123)  #=> "7B"
sprintf("%#X", 123) #=> "0X7B"

# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123)   #=> "1111011"
sprintf("%#b", 123)  #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123)  #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0)    #=> "0"

# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123)  #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"

# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1)  #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"

# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234)  #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."

# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4)   #=> "123.4"
sprintf("%#g", 123.4)  #=> "123.400"
sprintf("%g", 123456)  #=> "123456"
sprintf("%#g", 123456) #=> "123456."

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

# padding is done by spaces,       width=20
# 0 or radix-1.             <------------------>
sprintf("%20d", 123)   #=> "                 123"
sprintf("%+20d", 123)  #=> "                +123"
sprintf("%020d", 123)  #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123)  #=> "123                 "
sprintf("%-+20d", 123) #=> "+123                "
sprintf("%- 20d", 123) #=> " 123                "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"

For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

Examples of precisions:

# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits               <------>
sprintf("%20.8d", 123)  #=> "            00000123"
sprintf("%20.8o", 123)  #=> "            00000173"
sprintf("%20.8x", 123)  #=> "            0000007b"
sprintf("%20.8b", 123)  #=> "            01111011"
sprintf("%20.8d", -123) #=> "           -00000123"
sprintf("%20.8o", -123) #=> "            ..777605"
sprintf("%20.8x", -123) #=> "            ..ffff85"
sprintf("%20.8b", -11)  #=> "            ..110101"

# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted.  <------>
sprintf("%#20.8d", 123)  #=> "            00000123"
sprintf("%#20.8o", 123)  #=> "            00000173"
sprintf("%#20.8x", 123)  #=> "          0x0000007b"
sprintf("%#20.8b", 123)  #=> "          0b01111011"
sprintf("%#20.8d", -123) #=> "           -00000123"
sprintf("%#20.8o", -123) #=> "            ..777605"
sprintf("%#20.8x", -123) #=> "          0x..ffff85"
sprintf("%#20.8b", -11)  #=> "          0b..110101"

# precision for `e' is number of
# digits after the decimal point           <------>
sprintf("%20.8e", 1234.56789) #=> "      1.23456789e+03"

# precision for `f' is number of
# digits after the decimal point               <------>
sprintf("%20.8f", 1234.56789) #=> "       1234.56789000"

# precision for `g' is number of
# significant digits                          <------->
sprintf("%20.8g", 1234.56789) #=> "           1234.5679"

#                                         <------->
sprintf("%20.8g", 123456789)  #=> "       1.2345679e+08"

# precision for `s' is
# maximum number of characters                    <------>
sprintf("%20.8s", "string test") #=> "            string t"

Examples:

sprintf("%d %04x", 123, 123)               #=> "123 007b"
sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
sprintf("%u", -123)                        #=> "-123"

For more complex formatting, Ruby supports a reference by name. %s style uses format style, but %name style doesn't.

Exapmles:

sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
  #=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
  # => "1f"

Overloads:

+ (Boolean) framework(framework_name)

Loads a framework which specified a framework_name. Returns a true if loaded a framework. Otherwise, returns a false.

framework 'Foundation'

Returns:

  • (Boolean)

+ (String) getpass(prompt)

Displays a prompt which passed prompt as String to /dev/tty, and returns a string which read a password from /dev/tty.

Returns:

+ (String?) gets(sep = $/) + (String?) gets(limit) + (String?) gets(sep, limit)

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV, gets(nil) will read the contents one file at a time.

ARGV << "testfile"
print while gets

produces:

This is line one
This is line two
This is line three
And so on...

The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.

Overloads:

  • + gets

    Returns:

  • + gets

    Returns:

  • + gets

    Returns:

+ (Array) global_variables

Returns an array of the names of global variables.

global_variables.grep /std/   #=> [:$stdin, :$stdout, :$stderr]

Returns:

+ (Object) initialize

Initializes the receiver before it’s used (before it receives its first message). The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

Returns:

+ (IMP) instanceMethodForSelector(aSelector)

Locates and returns the address of the implementation of the instance method identified by a given selector. An error is generated if instances of the receiver can’t respond to aSelector messages.Use this method to ask the class object for the implementation of instance methods only. To ask the class for the implementation of a class method, send the methodForSelector: instance method to the class instead.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method for which to return the implementation address. The selector must be non-NULL and valid for the receiver. If in doubt, use the respondsToSelector: method to check before passing the selector to methodForSelector:.

Returns:

  • (IMP)

    The address of the implementation of the aSelector instance method.

+ (NSMethodSignature) instanceMethodSignatureForSelector(aSelector)

Returns an NSMethodSignature object that contains a description of the instance method identified by a given selector.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method for which to return the implementation address.

Returns:

+ (Boolean) instancesRespondToSelector(aSelector)

Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector. If aSelector messages are forwarded to other objects, instances of the class are able to receive those messages without error even though this method returns NO.To ask the class whether it, rather than its instances, can respond to a particular message, send to the class instead the NSObject protocol instance method respondsToSelector:.

Parameters:

  • aSelector (Symbol)

    A selector.

Returns:

  • (Boolean)

    YES if instances of the receiver are capable of responding to aSelector messages, otherwise NO.

+ (Boolean) isSubclassOfClass(aClass)

Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.

Parameters:

  • aClass (Class)

    A class object.

Returns:

  • (Boolean)

    YES if the receiving class is a subclass of—or identical to—aClass, otherwise NO.

+ (Boolean) block_given? + (Boolean) iterator?

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

def try
  if block_given?
    yield
  else
    "no block"
  end
end
try                  #=> "no block"
try { "hello" }      #=> "hello"
try do "hello" end   #=> "hello"

Overloads:

  • + block_given?

    Returns:

    • (Boolean)
  • + iterator?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

+ (Proc) lambda {|...| ... }

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Yields:

  • (...)

Returns:

+ (Object) load

Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading. The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.The order of initialization is as follows:All initializers in any framework you link to.All +load methods in your image.All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.All initializers in frameworks that link to you.In addition:A class’s +load method is called after all of its superclasses’ load methods.A category load method is called after the class’s own +load method.In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.

Returns:

+ (Object) load_bridge_support_file(filename)

Loads a Bridge Support in the file filename.

Bridge Support is an FFI interface that MacRuby uses to provide a native interface for some C functions, structures and constants.

+ (Object) load_plist(string)

Returns a ruby object which is converted from string of plist format.

data = File.read('info.plist')
load_plist(data)          #=> {"CFBundleName"=>"${PRODUCT_NAME}", .... }

Returns:

+ (Array) local_variables

Returns the names of the current local variables.

fred = 1
for i in 1..10
   # ...
end
local_variables   #=> [:fred, :i]

Returns:

+ (Object) loop { ... } + (Enumerator) loop

Repeatedly executes the block.

If no block is given, an enumerator is returned instead.

loop do
  print "Input: "
  line = gets
  break if !line or line =~ /^qQ/
  # ...
end

StopIteration raised in the block breaks the loop.

Overloads:

  • + loop { ... }

    Yields:

  • + loop

    Returns:

+ (Object) mutableCopyWithZone(zone)

Returns the receiver. This method exists so class objects can be used in situations where you need an object that conforms to the NSMutableCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.

Parameters:

  • zone (NSZone)

    The memory zone in which to create the copy of the receiver.

Returns:

+ (Object) new

Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object. This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.

Returns:

  • (Object)

    A new instance of the receiver.

+ (IO?) open(path[, mode_enc [, perm]]) + (Object) open(path[, mode_enc [, perm]]) {|io| ... }

Creates an IO object connected to the given stream, file, or subprocess.

If path does not start with a pipe character ("|"), treat it as the name of a file to open using the specified mode (defaulting to "r").

The mode_enc is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either "mode", "mode:ext_enc", or "mode:ext_enc:int_enc". The mode is one of the following:

r: read (default)
w: write
a: append

The mode can be followed by "b" (means binary-mode), or "+" (means both reading and writing allowed) or both. If ext_enc (external encoding) is specified, read string will be tagged by the encoding in reading, and output string will be converted to the specified encoding in writing. If two encoding names, ext_enc and int_enc (external encoding and internal encoding), are specified, the read string is converted from ext_enc to int_enc then tagged with the int_enc in read mode, and in write mode, the output string will be converted from int_enc to ext_enc before writing.

If a file is being created, its initial permissions may be set using the integer third parameter.

If a block is specified, it will be invoked with the File object as a parameter, and the file will be automatically closed when the block terminates. The call returns the value of the block.

If path starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following the "|" is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not "-", the subprocess runs the command. If a block is associated with an open("|-") call, that block will be run twice---once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent's IO object will be connected to the child's $stdin and $stdout. The subprocess will be terminated at the end of the block.

open("testfile") do |f|
  print f.gets
end

produces:

This is line one

Open a subprocess and read its output:

cmd = open("|date")
print cmd.gets
cmd.close

produces:

Wed Apr  9 08:56:31 CDT 2003

Open a subprocess running the same Ruby program:

f = open("|-", "w+")
if f == nil
  puts "in Child"
  exit
else
  puts "Got: #{f.gets}"
end

produces:

Got: in Child

Open a subprocess using a block to receive the I/O object:

open("|-") do |f|
  if f == nil
    puts "in Child"
  else
    puts "Got: #{f.gets}"
  end
end

produces:

Got: in Child

Overloads:

  • + open

    Returns:

    • (IO, nil)
  • + open {|io| ... }

    Yields:

    • (io)

    Returns:

+ (Object) p(obj) + (Array) p(obj1, obj2, ...) + (nil) p

For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.

S = Struct.new(:name, :state)
s = S['dave', 'TX']
p s

produces:

#<S name="dave", state="TX">

Overloads:

  • + p

    Returns:

  • + p

    Returns:

  • + p

    Returns:

    • (nil)

Prints each object in turn to $stdout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method.

print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99

produces:

cat12399
cat, 1, 2, 3, 99

Returns:

  • (nil)

+ (nil) printf(io, string[, obj ... ]) + (nil) printf(string[, obj ... ])

Equivalent to:

io.write(sprintf(string, obj, ...)

or

$stdout.write(sprintf(string, obj, ...)

Overloads:

  • + printf

    Returns:

    • (nil)
  • + printf

    Returns:

    • (nil)

+ (Proc) proc {|...| ... }

Equivalent to Proc.new.

Yields:

  • (...)

Returns:

+ (Integer) putc(int)

Equivalent to:

$stdout.putc(int)

Refer to the documentation for IO#putc for important information regarding multi-byte characters.

Returns:

+ (nil) puts(obj, ...)

Equivalent to

$stdout.puts(obj, ...)

Returns:

  • (nil)

+ (Object) raise + (Object) raise(string) + (Object) raise(exception[, string [, array]]) + (Object) fail + (Object) fail(string) + (Object) fail(exception[, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller

+ (Numeric) rand(max = 0) + (Float) rand + (Numeric) rand(limit)

If max is Range, returns a pseudorandom number where range.member(number) == true.

Or else converts max to an integer using max1 = max.to_i.abs.

Then if max is nil the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0.

Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1.

Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.

srand 1234                 #=> 0
[ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
[ rand(10), rand(1000) ]   #=> [6, 817]
srand 1234                 #=> 1234
[ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]

Overloads:

+ (String) readline(sep = $/) + (String) readline(limit) + (String) readline(sep, limit)

Equivalent to Kernel::gets, except readline raises EOFError at end of file.

Overloads:

+ (Array) readlines(sep = $/) + (Array) readlines(limit) + (Array) readlines(sep, limit)

Returns an array containing the lines returned by calling Kernel.gets(sep) until the end of file.

Overloads:

  • + readlines

    Returns:

  • + readlines

    Returns:

  • + readlines

    Returns:

+ (Boolean) require(name)

Loads the given name, returning true if successful and false if the feature is already loaded.

If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $LOAD_PATH ($:).

If the filename has the extension ".rb", it is loaded as a source file; if the extension is ".so", ".o", or ".dll", or the default shared library extension on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on to the name until found. If the file named cannot be found, a LoadError will be raised.

For Ruby extensions the filename given may use any shared library extension. For example, on Linux the socket extension is "socket.so" and require 'socket.dll' will load the socket extension.

The absolute path of the loaded file is added to $LOADED_FEATURES ($"). A file will not be loaded again if its path already appears in $". For example, require 'a'; require './a' will not load a.rb again.

require "my-library.rb"
require "db-driver"

Returns:

  • (Boolean)

+ (Boolean) resolveClassMethod(name)

Dynamically provides an implementation for a given selector for a class method. This method allows you to dynamically provide an implementation for a given selector. See resolveInstanceMethod: for further discussion.

Parameters:

  • name (Symbol)

    The name of a selector to resolve.

Returns:

  • (Boolean)

    YES if the method was found and added to the receiver, otherwise NO.

+ (Boolean) resolveInstanceMethod(name)

Dynamically provides an implementation for a given selector for an instance method. This method and resolveClassMethod: allow you to dynamically provide an implementation for a given selector.An Objective-C method is simply a C function that take at least two arguments—self and _cmd. Using the class_addMethod function, you can add a function to a class as a method. Given the following function:you can use resolveInstanceMethod: to dynamically add it to a class as a method (called resolveThisMethodDynamically) like this:

Parameters:

  • name (Symbol)

    The name of a selector to resolve.

Returns:

  • (Boolean)

    YES if the method was found and added to the receiver, otherwise NO.

+ (Object) select(read_array)

[, error_array

[, timeout]]] )-> array  or  nil

See Kernel#select.

+ (Object) setVersion(aVersion)

Sets the receiver's version number. The version number is helpful when instances of the class are to be archived and reused later. The default version is 0.

Parameters:

  • aVersion (Integer)

    The version number for the receiver.

Returns:

+ (String) format(format_string[, arguments...]) + (String) sprintf(format_string[, arguments...])

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result.

The syntax of a format sequence is follows.

%[flags][width][.precision]type

A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.

The field type characters are:

Field |  Integer Format
------+--------------------------------------------------------------
  b   | Convert argument as a binary number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..1'.
  B   | Equivalent to `b', but uses an uppercase 0B for prefix
      | in the alternative format by #.
  d   | Convert argument as a decimal number.
  i   | Identical to `d'.
  o   | Convert argument as an octal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..7'.
  u   | Identical to `d'.
  x   | Convert argument as a hexadecimal number.
      | Negative numbers will be displayed as a two's complement
      | prefixed with `..f' (representing an infinite string of
      | leading 'ff's).
  X   | Equivalent to `x', but uses uppercase letters.

Field |  Float Format
------+--------------------------------------------------------------
  e   | Convert floating point argument into exponential notation
      | with one digit before the decimal point as [-]d.dddddde[+-]dd.
      | The precision specifies the number of digits after the decimal
      | point (defaulting to six).
  E   | Equivalent to `e', but uses an uppercase E to indicate
      | the exponent.
  f   | Convert floating point argument as [-]ddd.dddddd,
      | where the precision specifies the number of digits after
      | the decimal point.
  g   | Convert a floating point number using exponential form
      | if the exponent is less than -4 or greater than or
      | equal to the precision, or in dd.dddd form otherwise.
      | The precision specifies the number of significant digits.
  G   | Equivalent to `g', but use an uppercase `E' in exponent form.
  a   | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
      | which is consisted from optional sign, "0x", fraction part
      | as hexadecimal, "p", and exponential part as decimal.
  A   | Equivalent to `a', but use uppercase `X' and `P'.

Field |  Other Format
------+--------------------------------------------------------------
  c   | Argument is the numeric code for a single character or
      | a single character string itself.
  p   | The valuing of argument.inspect.
  s   | Argument is a string to be substituted.  If the format
      | sequence contains a precision, at most that many characters
      | will be copied.
  %   | A percent sign itself will be displayed.  No argument taken.

The flags modifies the behavior of the formats. The flag characters are:

Flag     | Applies to    | Meaning
---------+---------------+-----------------------------------------
space    | bBdiouxX      | Leave a space at the start of
         | aAeEfgG       | non-negative numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
(digit)$ | all           | Specifies the absolute argument number
         |               | for this field.  Absolute and relative
         |               | argument numbers cannot be mixed in a
         |               | sprintf string.
---------+---------------+-----------------------------------------
 #       | bBoxX         | Use an alternative format.
         | aAeEfgG       | For the conversions `o', increase the precision
         |               | until the first digit will be `0' if
         |               | it is not formatted as complements.
         |               | For the conversions `x', `X', `b' and `B'
         |               | on non-zero, prefix the result with ``0x'',
         |               | ``0X'', ``0b'' and ``0B'', respectively.
         |               | For `a', `A', `e', `E', `f', `g', and 'G',
         |               | force a decimal point to be added,
         |               | even if no digits follow.
         |               | For `g' and 'G', do not remove trailing zeros.
---------+---------------+-----------------------------------------
+        | bBdiouxX      | Add a leading plus sign to non-negative
         | aAeEfgG       | numbers.
         | (numeric fmt) | For `o', `x', `X', `b' and `B', use
         |               | a minus sign with absolute value for
         |               | negative values.
---------+---------------+-----------------------------------------
-        | all           | Left-justify the result of this conversion.
---------+---------------+-----------------------------------------
0 (zero) | bBdiouxX      | Pad with zeros, not spaces.
         | aAeEfgG       | For `o', `x', `X', `b' and `B', radix-1
         | (numeric fmt) | is used for negative numbers formatted as
         |               | complements.
---------+---------------+-----------------------------------------
*        | all           | Use the next argument as the field width.
         |               | If negative, left-justify the result. If the
         |               | asterisk is followed by a number and a dollar
         |               | sign, use the indicated argument as the width.

Examples of flags:

# `+' and space flag specifies the sign of non-negative numbers.
sprintf("%d", 123)  #=> "123"
sprintf("%+d", 123) #=> "+123"
sprintf("% d", 123) #=> " 123"

# `#' flag for `o' increases number of digits to show `0'.
# `+' and space flag changes format of negative numbers.
sprintf("%o", 123)   #=> "173"
sprintf("%#o", 123)  #=> "0173"
sprintf("%+o", -123) #=> "-173"
sprintf("%o", -123)  #=> "..7605"
sprintf("%#o", -123) #=> "..7605"

# `#' flag for `x' add a prefix `0x' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%x", 123)   #=> "7b"
sprintf("%#x", 123)  #=> "0x7b"
sprintf("%+x", -123) #=> "-7b"
sprintf("%x", -123)  #=> "..f85"
sprintf("%#x", -123) #=> "0x..f85"
sprintf("%#x", 0)    #=> "0"

# `#' for `X' uses the prefix `0X'.
sprintf("%X", 123)  #=> "7B"
sprintf("%#X", 123) #=> "0X7B"

# `#' flag for `b' add a prefix `0b' for non-zero numbers.
# `+' and space flag disables complements for negative numbers.
sprintf("%b", 123)   #=> "1111011"
sprintf("%#b", 123)  #=> "0b1111011"
sprintf("%+b", -123) #=> "-1111011"
sprintf("%b", -123)  #=> "..10000101"
sprintf("%#b", -123) #=> "0b..10000101"
sprintf("%#b", 0)    #=> "0"

# `#' for `B' uses the prefix `0B'.
sprintf("%B", 123)  #=> "1111011"
sprintf("%#B", 123) #=> "0B1111011"

# `#' for `e' forces to show the decimal point.
sprintf("%.0e", 1)  #=> "1e+00"
sprintf("%#.0e", 1) #=> "1.e+00"

# `#' for `f' forces to show the decimal point.
sprintf("%.0f", 1234)  #=> "1234"
sprintf("%#.0f", 1234) #=> "1234."

# `#' for `g' forces to show the decimal point.
# It also disables stripping lowest zeros.
sprintf("%g", 123.4)   #=> "123.4"
sprintf("%#g", 123.4)  #=> "123.400"
sprintf("%g", 123456)  #=> "123456"
sprintf("%#g", 123456) #=> "123456."

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Examples of width:

# padding is done by spaces,       width=20
# 0 or radix-1.             <------------------>
sprintf("%20d", 123)   #=> "                 123"
sprintf("%+20d", 123)  #=> "                +123"
sprintf("%020d", 123)  #=> "00000000000000000123"
sprintf("%+020d", 123) #=> "+0000000000000000123"
sprintf("% 020d", 123) #=> " 0000000000000000123"
sprintf("%-20d", 123)  #=> "123                 "
sprintf("%-+20d", 123) #=> "+123                "
sprintf("%- 20d", 123) #=> " 123                "
sprintf("%020x", -123) #=> "..ffffffffffffffff85"

For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

Examples of precisions:

# precision for `d', 'o', 'x' and 'b' is
# minimum number of digits               <------>
sprintf("%20.8d", 123)  #=> "            00000123"
sprintf("%20.8o", 123)  #=> "            00000173"
sprintf("%20.8x", 123)  #=> "            0000007b"
sprintf("%20.8b", 123)  #=> "            01111011"
sprintf("%20.8d", -123) #=> "           -00000123"
sprintf("%20.8o", -123) #=> "            ..777605"
sprintf("%20.8x", -123) #=> "            ..ffff85"
sprintf("%20.8b", -11)  #=> "            ..110101"

# "0x" and "0b" for `#x' and `#b' is not counted for
# precision but "0" for `#o' is counted.  <------>
sprintf("%#20.8d", 123)  #=> "            00000123"
sprintf("%#20.8o", 123)  #=> "            00000173"
sprintf("%#20.8x", 123)  #=> "          0x0000007b"
sprintf("%#20.8b", 123)  #=> "          0b01111011"
sprintf("%#20.8d", -123) #=> "           -00000123"
sprintf("%#20.8o", -123) #=> "            ..777605"
sprintf("%#20.8x", -123) #=> "          0x..ffff85"
sprintf("%#20.8b", -11)  #=> "          0b..110101"

# precision for `e' is number of
# digits after the decimal point           <------>
sprintf("%20.8e", 1234.56789) #=> "      1.23456789e+03"

# precision for `f' is number of
# digits after the decimal point               <------>
sprintf("%20.8f", 1234.56789) #=> "       1234.56789000"

# precision for `g' is number of
# significant digits                          <------->
sprintf("%20.8g", 1234.56789) #=> "           1234.5679"

#                                         <------->
sprintf("%20.8g", 123456789)  #=> "       1.2345679e+08"

# precision for `s' is
# maximum number of characters                    <------>
sprintf("%20.8s", "string test") #=> "            string t"

Examples:

sprintf("%d %04x", 123, 123)               #=> "123 007b"
sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
sprintf("%u", -123)                        #=> "-123"

For more complex formatting, Ruby supports a reference by name. %s style uses format style, but %name style doesn't.

Exapmles:

sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
  #=> 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })
  # => "1f"

Overloads:

+ (Object) srand(number = 0)

Seeds the pseudorandom number generator to the value of number. If number is omitted, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.

+ (Class) superclass

Returns the class object for the receiver’s superclass.

Returns:

  • (Class)

    The class object for the receiver’s superclass.

+ (Object) test(int_cmd, file1[, file2])

Uses the integer aCmd to perform various tests on file1 (first table below) or on file1 and file2 (second table).

File tests on a single file:

Test   Returns   Meaning
"A"  | Time    | Last access time for file1
"b"  | boolean | True if file1 is a block device
"c"  | boolean | True if file1 is a character device
"C"  | Time    | Last change time for file1
"d"  | boolean | True if file1 exists and is a directory
"e"  | boolean | True if file1 exists
"f"  | boolean | True if file1 exists and is a regular file
"g"  | boolean | True if file1 has the \CF{setgid} bit
     |         | set (false under NT)
"G"  | boolean | True if file1 exists and has a group
     |         | ownership equal to the caller's group
"k"  | boolean | True if file1 exists and has the sticky bit set
"l"  | boolean | True if file1 exists and is a symbolic link
"M"  | Time    | Last modification time for file1
"o"  | boolean | True if file1 exists and is owned by
     |         | the caller's effective uid
"O"  | boolean | True if file1 exists and is owned by
     |         | the caller's real uid
"p"  | boolean | True if file1 exists and is a fifo
"r"  | boolean | True if file1 is readable by the effective
     |         | uid/gid of the caller
"R"  | boolean | True if file is readable by the real
     |         | uid/gid of the caller
"s"  | int/nil | If file1 has nonzero size, return the size,
     |         | otherwise return nil
"S"  | boolean | True if file1 exists and is a socket
"u"  | boolean | True if file1 has the setuid bit set
"w"  | boolean | True if file1 exists and is writable by
     |         | the effective uid/gid
"W"  | boolean | True if file1 exists and is writable by
     |         | the real uid/gid
"x"  | boolean | True if file1 exists and is executable by
     |         | the effective uid/gid
"X"  | boolean | True if file1 exists and is executable by
     |         | the real uid/gid
"z"  | boolean | True if file1 exists and has a zero length

Tests that take two files:

"-"  | boolean | True if file1 and file2 are identical
"="  | boolean | True if the modification times of file1
     |         | and file2 are equal
"<"  | boolean | True if the modification time of file1
     |         | is prior to that of file2
">"  | boolean | True if the modification time of file1
     |         | is after that of file2

Returns:

+ (Object) throw(tag[, obj])

Transfers control to the end of the active catch block waiting for tag. Raises ArgumentError if there is no catch block for the tag. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.

+ (nil) trace_var(symbol, cmd) + (nil) trace_var(symbol) {|val| ... }

Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable's new value as a parameter. Also see Kernel::untrace_var.

trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
$_ = "hello"
$_ = ' there'

produces:

$_ is now 'hello'
$_ is now ' there'

Overloads:

  • + trace_var

    Returns:

    • (nil)
  • + trace_var {|val| ... }

    Yields:

    • (val)

    Returns:

    • (nil)

+ (Object) trap(signal, command) + (Object) trap(signal) {|| ... }

Specifies the handling of signals. The first parameter is a signal name (a string such as "SIGALRM", "SIGUSR1", and so on) or a signal number. The characters "SIG" may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string "IGNORE" or "SIG_IGN", the signal will be ignored. If the command is "DEFAULT" or "SIG_DFL", the Ruby's default handler will be invoked. If the command is "EXIT", the script will be terminated by the signal. If the command is "SYSTEM_DEFAULT", the operating system's default handler will be invoked. Otherwise, the given command or block will be run. The special signal name "EXIT" or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD")  { puts "Child died" }
fork && Process.wait

produces:

Terminating: 27461
Child died
Terminating: 27460

Overloads:

  • + trap

    Returns:

  • + trap {|| ... }

    Yields:

    • ()

    Returns:

+ (Array?) untrace_var(symbol[, cmd])

Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.

Returns:

+ (Integer) version

Returns the version number assigned to the class. If no version has been set, the default is 0. Version numbers are needed for decoding or unarchiving, so older versions of an object can be detected and decoded correctly.Caution should be taken when obtaining the version from within an NSCoding protocol or other methods. Use the class name explicitly when getting a class version number: Don’t simply send version to the return value of class—a subclass version number may be returned instead.

Returns:

  • (Integer)

    The version number assigned to the class.

Instance Method Details

- (Object) !

Boolean negate.

- (Object) !=

Returns true if two objects are not-equal, otherwise false.

- (Object) !~

Returns true if two objects do not match (using the =~ method), otherwise false.

- (0?) <=>(other)

Returns 0 if obj === other, otherwise nil.

Returns:

  • (0, nil)

- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

Overloads:

  • - ==

    Returns:

    • (Boolean)
  • - equal?

    Returns:

    • (Boolean)
  • - eql?

    Returns:

    • (Boolean)

- (Boolean) ===(other)

Case Equality---For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

Returns:

  • (Boolean)

- (nil) =~(other)

Pattern Match---Overridden by descendants (notably Regexp and String) to provide meaningful pattern-match semantics.

Returns:

  • (nil)

- (Symbol) __method__ - (Symbol) __callee__

Returns the name of the current method as a Symbol. If called outside of a method, it returns nil.

Overloads:

  • - __method__

    Returns:

  • - __callee__

    Returns:

- (Symbol) __method__ - (Symbol) __callee__

Returns the name of the current method as a Symbol. If called outside of a method, it returns nil.

Overloads:

  • - __method__

    Returns:

  • - __callee__

    Returns:

- (Object) send(symbol[, args...]) - (Object) __send__(symbol[, args...])

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end
k = Klass.new
k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

Overloads:

- (Object) __type__

:nodoc:

- (Object) autoContentAccessingProxy

Creates and returns a proxy for the receiving object This method creates and returns a proxy for the receiving object, if the receiver adopts the NSDiscardableContent protocol and still has undiscarded content.The proxy calls beginContentAccess on the receiver to keep the content available as long as the proxy lives, and calls endContentAccess when the proxy is deallocated.The wrapper object is otherwise a subclass of NSProxy and forwards messages to the original receiver object as an NSProxy does. This method can be used to hide an NSDiscardableContent object's content volatility by creating an object that responds to the same messages but holds the contents of the original receiver available as long as the created proxy lives. Thus hidden, the NSDiscardableContent object (by way of the proxy) can be given out to unsuspecting recipients of the object who would otherwise not know they might have to call beginContentAccess and endContentAccess around particular usages (specific to each NSDiscardableContent object) of the NSDiscardableContent object.

Returns:

  • (Object)

    A proxy of the receiver.

- (Object) awakeAfterUsingCoder(aDecoder)

Overridden by subclasses to substitute another object in place of the object that was decoded and subsequently received this message. You can use this method to eliminate redundant objects created by the coder. For example, if after decoding an object you discover that an equivalent object already exists, you can return the existing object. If a replacement is returned, your overriding method is responsible for releasing the receiver. This method is invoked by NSCoder. NSObject’s implementation simply returns self.

Parameters:

  • aDecoder (NSCoder)

    The decoder used to decode the receiver.

Returns:

  • (Object)

    The receiver, or another object to take the place of the object that was decoded and subsequently received this message.

- (Class) classForCoder

Overridden by subclasses to substitute a class other than its own during coding. This method is invoked by NSCoder. NSObject’s implementation returns the receiver’s class. The private subclasses of a class cluster substitute the name of their public superclass when being archived.

Returns:

  • (Class)

    The class to substitute for the receiver’s own class during coding.

- (Class) classForKeyedArchiver

Overridden by subclasses to substitute a new class for instances during keyed archiving. The object will be encoded as if it were a member of the returned class. The results of this method are overridden by the encoder class and instance name to class encoding tables. If nil is returned, the result of this method is ignored.

Returns:

- (Object) clone

Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.

class Klass
   attr_accessor :str
end
s1 = Klass.new      #=> #<Klass:0x401b3a38>
s1.str = "Hello"    #=> "Hello"
s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i"   #=> "i"
s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Returns:

- (Object) copy

Returns the object returned by copyWithZone:. This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

Returns:

  • (Object)

    The object returned by the NSCopying protocol method copyWithZone:,.

- (Object) dealloc

Deallocates the memory occupied by the receiver. Subsequent messages to the receiver may generate an error indicating that a message was sent to a deallocated object (provided the deallocated memory hasn’t been reused yet).You override this method to dispose of resources other than the object’s instance variables, for example:In an implementation of dealloc, do not invoke the superclass’s implementation. Typically you should try to avoid managing the lifetime of resources such as file descriptors using dealloc.You never send a dealloc message directly. Instead, an object’s dealloc method is invoked by the runtime. See Advanced Memory Management Programming Guide for more details.

Returns:

- (Method) define_singleton_method(symbol, method) - (Proc) define_singleton_method(symbol) { ... }

Defines a singleton method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body.

class A
  class << self
    def class_name
      to_s
    end
  end
end
A.define_singleton_method(:who_am_i) do
  "I am: #{class_name}"
end
A.who_am_i   # ==> "I am: A"

guy = "Bob"
guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
guy.hello    #=>  "Bob: Hello there!"

Overloads:

  • - define_singleton_method

    Returns:

  • - define_singleton_method { ... }

    Yields:

    Returns:

- (Object) doesNotRecognizeSelector(aSelector)

Handles messages the receiver doesn’t recognize. The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward. This method, in turn, raises an NSInvalidArgumentException, and generates an error message. Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, an NSObject subclass might renounce the copy or init method by re-implementing it to include a doesNotRecognizeSelector: message as follows:The _cmd variable is a hidden argument passed to every method that is the current selector; in this example, it identifies the selector for the copy method. This code prevents instances of the subclass from responding to copy messages or superclasses from forwarding copy messages—although respondsToSelector: will still report that the receiver has access to a copy method.If you override this method, you must call super or raise an NSInvalidArgumentException exception at the end of your implementation. In other words, this method must not return normally; it must always result in an exception being thrown.

Parameters:

  • aSelector (Symbol)

    A selector that identifies a method not implemented or recognized by the receiver.

Returns:

- (Object) dup

Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Returns:

- (Object) to_enum(method = :each, *args) - (Object) enum_for(method = :each, *args)

Creates a new Enumerator which will enumerate by on calling method on obj.

method

the method to call on obj to generate the enumeration

args

arguments that will be passed in method in addition to the item itself. Note that the number of args must not exceed the number expected by method

Example

str = "xyz"

enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122

# protect an array from being modified by some_method
a = [1, 2, 3]
some_method(a.to_enum)

- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

Overloads:

  • - ==

    Returns:

    • (Boolean)
  • - equal?

    Returns:

    • (Boolean)
  • - eql?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Boolean) ==(other) - (Boolean) equal?(other) - (Boolean) eql?(other)

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

Overloads:

  • - ==

    Returns:

    • (Boolean)
  • - equal?

    Returns:

    • (Boolean)
  • - eql?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Object) extend

Adds to obj the instance methods from each module given as a parameter.

module Mod
  def hello
    "Hello from Mod.\n"
  end
end

class Klass
  def hello
    "Hello from Klass.\n"
  end
end

k = Klass.new
k.hello         #=> "Hello from Klass.\n"
k.extend(Mod)   #=> #<Klass:0x401b3bc8>
k.hello         #=> "Hello from Mod.\n"

Returns:

- (Object) finalize

The garbage collector invokes this method on the receiver before disposing of the memory it uses. (Deprecated. Garbage collection is deprecated in OS X v10.8; instead,you should use AutomaticReference Counting—see Transitioning to ARC Release Notes.) The garbage collector invokes this method on the receiver before disposing of the memory it uses. When garbage collection is enabled, this method is invoked instead of dealloc.You can override this method to relinquish resources the receiver has obtained, as shown in the following example:Typically, however, you are encouraged to relinquish resources prior to finalization if at all possible. For more details, see “Implementing a finalize Method”.

Returns:

- (Object) forwardingTargetForSelector(aSelector)

Returns the object to which unrecognized messages should first be directed. If an object implements (or inherits) this method, and returns a non-nil (and non-self) result, that returned object is used as the new receiver object and the message dispatch resumes to that new object. (Obviously if you return self from this method, the code would just fall into an infinite loop.)If you implement this method in a non-root class, if your class has nothing to return for the given selector then you should return the result of invoking super’s implementation. This method gives an object a chance to redirect an unknown message sent to it before the much more expensive forwardInvocation: machinery takes over. This is useful in basic proxying situations and can be an order of magnitude faster than regular forwarding. It is not useful where the goal of the forwarding is to capture the NSInvocation, or manipulate the arguments or return value during the forwarding.

Parameters:

  • aSelector (Symbol)

    A selector for a method that the receiver does not implement.

Returns:

  • (Object)

    The object to which unrecognized messages should first be directed.

- (Object) forwardInvocation(anInvocation)

Overridden by subclasses to forward messages to other objects. When an object is sent a message for which it has no corresponding method, the runtime system gives the receiver an opportunity to delegate the message to another receiver. It delegates the message by creating an NSInvocation object representing the message and sending the receiver a forwardInvocation: message containing this NSInvocation object as the argument. The receiver’s forwardInvocation: method can then choose to forward the message to another object. (If that object can’t respond to the message either, it too will be given a chance to forward it.)The forwardInvocation: message thus allows an object to establish relationships with other objects that will, for certain messages, act on its behalf. The forwarding object is, in a sense, able to “inherit” some of the characteristics of the object it forwards the message to.Important: To respond to methods that your object does not itself recognize, you must override methodSignatureForSelector: in addition to forwardInvocation:. The mechanism for forwarding messages uses information obtained from methodSignatureForSelector: to create the NSInvocation object to be forwarded. Your overriding method must provide an appropriate method signature for the given selector, either by preformulating one or by asking another object for one.An implementation of the forwardInvocation: method has two tasks:To locate an object that can respond to the message encoded in anInvocation. This object need not be the same for all messages. To send the message to that object using anInvocation. anInvocation will hold the result, and the runtime system will extract and deliver this result to the original sender.In the simple case, in which an object forwards messages to just one destination (such as the hypothetical friend instance variable in the example below), a forwardInvocation: method could be as simple as this:The message that’s forwarded must have a fixed number of arguments; variable numbers of arguments (in the style of printf()) are not supported.The return value of the forwarded message is returned to the original sender. All types of return values can be delivered to the sender: id types, structures, double-precision floating-point numbers. Implementations of the forwardInvocation: method can do more than just forward messages. forwardInvocation: can, for example, be used to consolidate code that responds to a variety of different messages, thus avoiding the necessity of having to write a separate method for each selector. A forwardInvocation: method might also involve several other objects in the response to a given message, rather than forward it to just one.NSObject’s implementation of forwardInvocation: simply invokes the doesNotRecognizeSelector: method; it doesn’t forward any messages. Thus, if you choose not to implement forwardInvocation:, sending unrecognized messages to objects will raise exceptions.

Parameters:

  • anInvocation (NSInvocation)

    The invocation to forward.

Returns:

- (Object) freeze

Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.

This method returns self.

a = [ "a", "b", "c" ]
a.freeze
a << "z"

produces:

prog.rb:3:in `<<': can't modify frozen array (RuntimeError)
  from prog.rb:3

Returns:

- (Boolean) frozen?

Returns the freeze status of obj.

a = [ "a", "b", "c" ]
a.freeze    #=> ["a", "b", "c"]
a.frozen?   #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) init

Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated. An init message is coupled with an alloc (or allocWithZone:) message in the same line of code:An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.In a custom implementation of this method, you must invoke super’s designated initializer then initialize and return the new object. If the new object can’t be initialized, the method should return nil.In some cases, an init method might return a substitute object. You must therefore always use the object returned by init, and not the one returned by alloc or allocWithZone:, in subsequent code.

Returns:

  • (Object)

    An initialized object.

- (Object) initialize_clone

:nodoc:

- (Object) initialize_copy

:nodoc:

- (Object) initialize_dup

:nodoc:

- (String) inspect

Returns a string containing a human-readable representation of obj. If not overridden and no instance variables, uses the to_s method to generate the string. obj. If not overridden, uses the to_s method to generate the string.

[ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
Time.new.inspect                 #=> "2008-03-08 19:43:39 +0900"

Returns:

- (Object) instance_eval(string[, filename [, lineno]]) - (Object) instance_eval {|| ... }

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj's instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

class KlassWithSecret
  def initialize
    @secret = 99
  end
end
k = KlassWithSecret.new
k.instance_eval { @secret }   #=> 99

Overloads:

  • - instance_eval

    Returns:

  • - instance_eval {|| ... }

    Yields:

    • ()

    Returns:

- (Object) instance_exec(arg...) {|var...| ... }

Executes the given block within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj's instance variables. Arguments are passed as block parameters.

class KlassWithSecret
  def initialize
    @secret = 99
  end
end
k = KlassWithSecret.new
k.instance_exec(5) {|x| @secret+x }   #=> 104

Yields:

  • (var...)

Returns:

- (Boolean) instance_of?

Returns true if obj is an instance of the given class. See also Object#kind_of?.

class A;     end
class B < A; end
class C < B; end

b = B.new
b.instance_of? A   #=> false
b.instance_of? B   #=> true
b.instance_of? C   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Boolean) instance_variable_defined?(symbol)

Returns true if the given instance variable is defined in obj.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_defined?(:@a)    #=> true
fred.instance_variable_defined?("@b")   #=> true
fred.instance_variable_defined?("@c")   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) instance_variable_get(symbol)

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a)    #=> "cat"
fred.instance_variable_get("@b")   #=> 99

Returns:

- (Object) instance_variable_set(symbol, obj)

Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class's author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_set(:@a, 'dog')   #=> "dog"
fred.instance_variable_set(:@c, 'cat')   #=> "cat"
fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"

Returns:

- (Array) instance_variables

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

class Fred
  attr_accessor :a1
  def initialize
    @iv = 3
  end
end
Fred.new.instance_variables   #=> [:@iv]

Returns:

- (Boolean) is_a? - (Boolean) kind_of?

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

module M;    end
class A
  include M
end
class B < A; end
class C < B; end

b = B.new
b.is_a? A          #=> true
b.is_a? B          #=> true
b.is_a? C          #=> false
b.is_a? M          #=> true

b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true

Overloads:

  • - is_a?

    Returns:

    • (Boolean)
  • - kind_of?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Boolean) is_a? - (Boolean) kind_of?

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

module M;    end
class A
  include M
end
class B < A; end
class C < B; end

b = B.new
b.is_a? A          #=> true
b.is_a? B          #=> true
b.is_a? C          #=> false
b.is_a? M          #=> true

b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true

Overloads:

  • - is_a?

    Returns:

    • (Boolean)
  • - kind_of?

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

- (Object) method(sym)

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj's object instance, so instance variables and the value of self remain available.

class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
m = k.method(:hello)
m.call   #=> "Hello, @iv = 99"

l = Demo.new('Fred')
m = l.method("hello")
m.call   #=> "Hello, @iv = Fred"

- (IMP) methodForSelector(aSelector)

Locates and returns the address of the receiver’s implementation of a method so it can be called as a function. If the receiver is an instance, aSelector should refer to an instance method; if the receiver is a class, it should refer to a class method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method for which to return the implementation address. The selector must be a valid and non-NULL. If in doubt, use the respondsToSelector: method to check before passing the selector to methodForSelector:.

Returns:

  • (IMP)

    The address of the receiver’s implementation of the aSelector.

- (Array) methods

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors.

class Klass
  def klass_method()
  end
end
k = Klass.new
k.methods[0..9]    #=> [:klass_method, :nil?, :===,
                   #    :==~, :!, :eql?
                   #    :hash, :<=>, :class, :singleton_class]
k.methods.length   #=> 57

Returns:

- (NSMethodSignature) methodSignatureForSelector(aSelector)

Returns an NSMethodSignature object that contains a description of the method identified by a given selector. This method is used in the implementation of protocols. This method is also used in situations where an NSInvocation object must be created, such as during message forwarding. If your object maintains a delegate or is capable of handling messages that it does not directly implement, you should override this method to return an appropriate method signature.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method for which to return the implementation address. When the receiver is an instance, aSelector should identify an instance method; when the receiver is a class, it should identify a class method.

Returns:

- (Object) mutableCopy

Returns the object returned by mutableCopyWithZone: where the zone is nil. This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.

Returns:

  • (Object)

    The object returned by the NSMutableCopying protocol method mutableCopyWithZone:, where the zone is nil.

- (Boolean) nil?

call_seq:

nil.nil?               -> true
<anything_else>.nil?   -> false

Only the object nil responds true to nil?.

Returns:

  • (Boolean)

- (Object) performSelector(aSelector, onThread:thr, withObject:arg, waitUntilDone:wait)

Invokes a method of the receiver on the specified thread using the default mode. You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread. This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • thr (NSThread)

    The thread on which to execute aSelector.

  • arg (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • wait (Boolean)

    A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the specified thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.If the current thread and target thread are the same, and you specify YES for this parameter, the selector is performed immediately on the current thread. If you specify NO, this method queues the message on the thread’s run loop and returns, just like it does for other threads. The current thread must then dequeue and process the message when it has an opportunity to do so.

Returns:

- (Object) performSelector(aSelector, onThread:thr, withObject:arg, waitUntilDone:wait, modes:array)

Invokes a method of the receiver on the specified thread using the specified modes. You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread. This method queues the message on the run loop of the target thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method. You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method instead.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. It should not have a significant return value and should take a single argument of type id, or no arguments.

  • thr (NSThread)

    The thread on which to execute aSelector. This thread represents the target thread.

  • arg (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • wait (Boolean)

    A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the specified thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.If the current thread and target thread are the same, and you specify YES for this parameter, the selector is performed immediately. If you specify NO, this method queues the message and returns immediately, regardless of whether the threads are the same or different.

  • array (Array)

    An array of strings that identifies the modes in which it is permissible to perform the specified selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Returns:

- (Object) performSelector(aSelector, withObject:anArgument, afterDelay:delay)

Invokes a method of the receiver on the current thread using the default mode after a delay. This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode. If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • anArgument (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • delay (NSTimeInterval)

    The minimum time before which the message is sent. Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

Returns:

- (Object) performSelector(aSelector, withObject:anArgument, afterDelay:delay, inModes:modes)

Invokes a method of the receiver on the current thread using the specified modes after a delay. This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the modes specified by the modes parameter. When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in one of the specified modes; otherwise, the timer waits until the run loop is in one of those modes. If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • anArgument (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • delay (NSTimeInterval)

    The minimum time before which the message is sent. Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

  • modes (Array)

    An array of strings that identify the modes to associate with the timer that performs the selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Returns:

- (Object) performSelectorInBackground(aSelector, withObject:arg)

Invokes a method of the receiver on a new background thread. This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program. For more information about how to configure and run threads, see Threading Programming Guide.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • arg (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

Returns:

- (Object) performSelectorOnMainThread(aSelector, withObject:arg, waitUntilDone:wait)

Invokes a method of the receiver on the main thread using the default mode. You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread. This method queues the message on the run loop of the main thread using the common run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the common run loop modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • arg (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • wait (Boolean)

    A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the main thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.If the current thread is also the main thread, and you specify YES for this parameter, the message is delivered and processed immediately.

Returns:

- (Object) performSelectorOnMainThread(aSelector, withObject:arg, waitUntilDone:wait, modes:array)

Invokes a method of the receiver on the main thread using the specified modes. You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread. This method queues the message on the run loop of the main thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made, assuming the associated run loop modes for each selector are the same. If you specify different modes for each selector, any selectors whose associated mode does not match the current run loop mode are skipped until the run loop subsequently executes in that mode.You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Parameters:

  • aSelector (Symbol)

    A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

  • arg (Object)

    The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

  • wait (Boolean)

    A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the main thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.If the current thread is also the main thread, and you pass YES, the message is performed immediately, otherwise the perform is queued to run the next time through the run loop.

  • array (Array)

    An array of strings that identifies the modes in which it is permissible to perform the specified selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Returns:

- (Array) private_methods(all = true)

Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:

- (Array) protected_methods(all = true)

Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:

- (Object) public_method(sym)

Similar to method, searches public method only.

- (Array) public_methods(all = true)

Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:

- (Object) public_send(symbol[, args...])

Invokes the method identified by symbol, passing it any arguments specified. Unlike send, public_send calls public methods only.

1.public_send(:puts, "hello")  # causes NoMethodError

Returns:

- (Numeric) Rational(x[, y])

Returns x/y;

Returns:

- (Object) replacementObjectForCoder(aCoder)

Overridden by subclasses to substitute another object for itself during encoding. An object might encode itself into an archive, but encode a proxy for itself if it’s being encoded for distribution. This method is invoked by NSCoder. NSObject’s implementation returns self.

Parameters:

  • aCoder (NSCoder)

    The coder encoding the receiver.

Returns:

  • (Object)

    The object encode instead of the receiver (if different).

- (Object) replacementObjectForKeyedArchiver(archiver)

Overridden by subclasses to substitute another object for itself during keyed archiving. This method is called only if no replacement mapping for the object has been set up in the encoder (for example, due to a previous call of replacementObjectForKeyedArchiver: to that object).

Parameters:

Returns:

  • (Object)

    The object encode instead of the receiver (if different).

- (Boolean) respond_to?(symbol, include_private = false)

Returns true if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

If the method is not implemented, as Process.fork on Windows, File.lchmod on GNU/Linux, etc., false is returned.

If the method is not defined, respond_to_missing? method is called and the result is returned.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Boolean) respond_to_missing?(symbol, include_private)

Hook method to return whether the obj can respond to id method or not.

See #respond_to?.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) send(symbol[, args...]) - (Object) __send__(symbol[, args...])

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end
k = Klass.new
k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

Overloads:

- (Array) singleton_methods(all = true)

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj. Only public and protected singleton methods are returned.

module Other
  def three() end
end

class Single
  def Single.four() end
end

a = Single.new

def a.one()
end

class << a
  include Other
  def two()
  end
end

Single.singleton_methods    #=> [:four]
a.singleton_methods(false)  #=> [:two, :one]
a.singleton_methods         #=> [:two, :one, :three]

Returns:

- (Object) taint

Marks obj as tainted---if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings.

Returns:

- (Boolean) tainted?

Returns true if the object is tainted.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) tap {|x| ... }

Yields x to the block, and then returns x. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

(1..10) .tap {|x| puts "original: #{x.inspect}"}

.to_a                .tap {|x| puts "array: #{x.inspect}"}
.select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
.map { |x| x*x }     .tap {|x| puts "squares: #{x.inspect}"}

Yields:

  • (x)

Returns:

- (String) to_plist

Returns a string of plist format which is converted from Object.

"foo".to_plist           #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<string>foo</string>\n</plist>\n"
{"foo" => 42}.to_plist   #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>foo</key>\n\t<integer>42</integer>\n</dict>\n</plist>\n"
["foo", "bar"].to_plist  #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<array>\n\t<string>foo</string>\n\t<string>bar</string>\n</array>\n</plist>\n"

Returns:

- (String) to_s

Returns a string representing obj. The default to_s prints the object's class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns "main."

Returns:

- (Object) trust

Removes the untrusted mark from obj.

Returns:

- (Object) untaint

Removes the taint from obj.

Returns:

- (Object) untrust

Marks obj as untrusted.

Returns:

- (Boolean) untrusted?

Returns true if the object is untrusted.

Returns:

  • (Boolean)

Returns:

  • (Boolean)